Intelligent Color Output

LESS allows our styles to be a little bit smarter. For example, we can make our styles “think” and decide what color to apply under certain conditions. Assuming we are creating a website template, this is the basic style button, and you plan to extend it with various colors and styles. But how can we control the color outputs? We certainly do not want the text color to be dark on a dark background, or vice versa. We need to ensure that the text retains contrast so that it is easier to read, and this is where the contrast() functions come into play.

@body-bg: #000;
body {
	background-color: @body-bg;
	color: contrast(@body-bg);
}

In the above example, we set the color through the contrast() function. This ensures that the text color has enough contrast against the background color. In this case, the text should return #fff since the background is #000. If you set the background to a light color, such as white, whitesmoke, or skyblue, the color should return #000.

body {
  background-color: #000;
  color: #fff;
}

You can also customize the color for dark and light contrast. In the following example, the color will return #999 or #777 in place of #fff and #000.

@body-bg : #f0f0f0;
@color-light : #999;
@color-dark  : #777;
 
body {
    background-color: @body-bg;
    color: contrast(@body-bg, @color-dark, @color-light);
}

Often, I also prefer not to output a style declaration if the color is transparent, especially for the background color. To do so, encapsulate the background declaration within LESS Mixin Guards.

@bg: transparent;
.element {
    & when not (@bg = transaprent) {
        background: @bg;
    }
}

You could also do the same for declaring border and color properties, and save a couple of lines in your stylesheet by eliminating unnecessary rules.

Paste it here