在深入研究颜色理论时,有一个叫做 相对颜色亮度 的概念。简单来说,颜色的亮度定义了它的亮度。亮度值为 1 表示颜色为白色。相反,亮度得分为 0 表示颜色为黑色。
了解颜色的亮度在处理动态或随机颜色时非常有用,以便在颜色过亮或过暗时提供准确的背景颜色。作为经验法则,您可以认为亮度超过 0.7 的颜色在白色背景上将难以阅读。
代码
/// Returns the luminance of `$color` as a float (between 0 and 1)
/// 1 is pure white, 0 is pure black
/// @param {Color} $color - Color
/// @return {Number}
/// @link http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef Reference
@function luminance($color) {
$colors: (
'red': red($color),
'green': green($color),
'blue': blue($color)
);
@each $name, $value in $colors {
$adjusted: 0;
$value: $value / 255;
@if $value < 0.03928 {
$value: $value / 12.92;
} @else {
$value: ($value + .055) / 1.055;
$value: pow($value, 2.4);
}
$colors: map-merge($colors, ($name: $value));
}
@return (map-get($colors, 'red') * .2126) + (map-get($colors, 'green') * .7152) + (map-get($colors, 'blue') * .0722);
}
用法
$color: #BADA55;
$luminance: luminance($color);
// 0.6123778773
嗨 Hugo,
我尝试测试亮度函数,但它不起作用。我们是否需要 Sass ally 插件才能使用亮度函数?
地图函数在 Sass 中默认是已知的,还是我们需要安装一个 gem 才能使用?
我尝试在 codepan 中测试亮度函数,但它不起作用。
我真的很期待您的回复。
干杯!
Rozita
您好。
您将需要
pow
函数:https://css-tricks.cn/snippets/sass/power-function/。:)谢谢,但是…
您想在哪里使用亮度变量?
这取决于您?:)
你知道,我放弃了:D
我决定使用 javascript 计算颜色的亮度,因为我使用的是 less,而且 less 中的助手和函数种类有限。
无论如何感谢您:)
这里没有提到,但最大的优势是将其用于 HSL https://en.wikipedia.org/wiki/HSL_and_HSV 和 HSLA https://css-tricks.cn/yay-for-hsla/
这就是 L 的含义,亮度:)
如果有人想知道如何部署它。我知道这个网站的流量很大,但新手可能不知道这一点。
HSL 中的 L 实际上代表“亮度”,它与亮度不同。
我更新了它以考虑 dart-sass 对使用
/
作为除法符号的新态度(请参见此处说明:)。注意使用
1.
@use 'sass:math';
调用相应的数学库。2.
math.div(number1, number2)
而不是(number1 / number2)
编辑:此处说明
https://sass-lang.com.cn/documentation/breaking-changes/slash-div