EN
SCSS - detect color blackness
3 points
In this article, we would like to show you how to detect color blackness in HWB color model using SCSS.
Quick solution:
xxxxxxxxxx
1
@use 'sass:color';
2
3
@if (color.blackness(red) > 50%) {
4
// ...
5
}
Where:
@use 'sass:color'
imports thecolor
module,color.blackness()
is a function that calculates blackness component value (between0%
and100%
) in HWB color model,red
is a color name that we use in blackness component value calculation.
In this example, we check $primary-color
blackness. If the blackness is greater than 50%
, we set the text color to white
, otherwise we set it to black
. This may be useful in web site conditional theming.
style.scss
file:
xxxxxxxxxx
1
@use 'sass:color';
2
3
$primary-color: black;
4
5
div.element {
6
background: $primary-color;
7
@if (color.blackness($primary-color) > 50%) {
8
color: white;
9
} @else {
10
color: black;
11
}
12
}
style.css
file (compiled from style.scss
):
xxxxxxxxxx
1
div.element {
2
background: black;
3
color: white;
4
}
Final result for two different $primary-color
values:
