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:
@use 'sass:color';
@if (color.blackness(red) > 50%) {
// ...
}
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.
Practical example
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:
@use 'sass:color';
$primary-color: black;
div.element {
background: $primary-color;
@if (color.blackness($primary-color) > 50%) {
color: white;
} @else {
color: black;
}
}
style.css
file (compiled from style.scss
):
div.element {
background: black;
color: white;
}
Final result for two different $primary-color
values: