Languages
[Edit]
EN

SCSS - detect color whiteness

0 points
Created by:
Aran-Busby
592

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 between 0% and 100%,
  • red  is a color value - it can be any color value - rgb / rgba / hex / color name / etc.
  • @use 'sass:color' imports the color 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:

SCSS / SASS - conditional text coloring (dark/light theme)
SCSS / SASS - conditional text coloring (dark/light theme)

See also

  1. SASS - detect color blackness

  2. SCSS / SASS - create project with Live Sass Compiler (VS Code)

References

  1. HWB color model - Wikipedia

Alternative titles

  1. SCSS / SASS - get / find / check color whiteness / lightness
  2. SCSS / SASS - detect color whiteness / lightness to determine styles
  3. SCSS / SASS - detect color whiteness / lightness in HWB color model
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join