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:
xxxxxxxxxx
1
@use 'sass:color';
2
3
@if (color.whiteness(red) < 50%) {
4
// ...
5
}
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.
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:
xxxxxxxxxx
1
@use 'sass:color';
2
3
$primary-color: black; /* color variable later assigned as the background of the element */
4
5
@mixin colorText($color) {
6
@if (color.whiteness($color) < 50%) {
7
color: white;
8
} @else {
9
color: black;
10
}
11
}
12
13
.element {
14
@include colorText($primary-color); /* sets the text color depending on $primary-color whiteness */
15
background: $primary-color;
16
}
The style.scss
file is compiled to style.css
:
xxxxxxxxxx
1
.element {
2
color: white;
3
background: black;
4
}
Final result for two different $primary-color
values:
