10

Is it possible to set a color based on the lightness/darkness of a less variable?

Currently I have the following code:

li {
    color: darken(@bodyBackground, 10%);
}

This works providing @bodyBackground is a light color. However if it was a dark color I'd like to use lighten(@bodyBackground, 10%). Is this possible with LESS?

2
  • 1
    See contrast function. Commented Feb 6, 2014 at 11:02
  • Yes, that does it. Can you add it as an answer please. Commented Feb 6, 2014 at 11:13

2 Answers 2

14

There's contrast function, e.g.:

li {
    color: contrast(@bodyBackground,
            lighten(@bodyBackground, 13%),
             darken(@bodyBackground, 13%));
}
Sign up to request clarification or add additional context in comments.

Comments

6

You can be much smarter than this. You can make a mixin to check the provided color, and perform either a darken or lighten depending on its color:

.smart-text-color (@a) when (lightness(@a) >= 50%) {
  // Its a light color return a dark output
  color: darken(@a, 60%);
}
.smart-text-color (@a) when (lightness(@a) < 50%) {
  // Its a dark color return a dark output
  color: lighten(@a, 60%);
}

Here is an example mixin, that takes the background color as the variable, and works out what text color to use. Returning either a light or dark output.

http://codepen.io/TristanBrotherton/pen/GwIgx?editors=110

3 Comments

And how is it smarter than contrast function?
It's much smarter since you can adjust multiple properties at once.
@gco, so you simply hardcode your mixin to a particular property set and then have to copy-paste the same code for each new set of properties? With each property duplicated? And how is this smarter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.