EN
SCSS - detect color whiteness
0
points
In this article, we would like to show you how to detect color whiteness in HWB model using SCSS.
Quick solution:
@use 'sass:color';
@if (color.whiteness(red) < 50%) {
// ...
}
Where:
whiteness()
is a function returns the HWB whiteness of$color
- value between0%
and100%
,red
is a color value - it can be any color value - rgb / rgba / hex / color name / etc.@use 'sass:color'
imports thecolor
module.
Practical example
In this example, we check if the whiteness of the $color
passed as argument to the colorText()
mixin is less than 50%
. If it is, we set the text color to white
, otherwise we set it to black
. This is very useful for themes on our web page.
Full example of style.scss
file:
@use 'sass:color';
$primary-color: black; /* color variable later assigned as the background of the element */
@mixin colorText($color) {
@if (color.whiteness($color) < 50%) {
color: white;
} @else {
color: black;
}
}
.element {
@include colorText($primary-color); /* sets the text color depending on $primary-color whiteness */
background: $primary-color;
}
The style.scss
file is compiled to style.css
:
.element {
color: white;
background: black;
}
Final result for two different $primary-color
values: