Languages
[Edit]
EN

SCSS - detect color blackness

3 points
Created by:
Kourtney-White
635

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 the color module,
  • color.blackness() is a function that calculates blackness component value (between 0% and 100%) 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:

Dark and light theme created using conditional text coloring in SCSS.
Dark and light theme created using conditional text coloring in SCSS.

 

See also

  1. SASS - detect color whiteness

  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 blackness / darkness
  2. SCSS / SASS- detect color blackness / darkness to determine styles
  3. SCSS / SASS - detect color blackness / darkness 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