Conditional CSS based on background color variable

和自甴很熟 提交于 2019-11-26 09:57:22

问题


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?


回答1:


There's contrast function, e.g.:

li {
    color: contrast(@bodyBackground,
            lighten(@bodyBackground, 13%),
             darken(@bodyBackground, 13%));
}



回答2:


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



来源:https://stackoverflow.com/questions/21600825/conditional-css-based-on-background-color-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!