"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can CSS Variables Mimic Sass's `darken()` Function for Color Shade Generation?

Can CSS Variables Mimic Sass's `darken()` Function for Color Shade Generation?

Posted on 2025-02-06
Browse:645

Can CSS Variables Mimic Sass's `darken()` Function for Color Shade Generation?

Color Shade Generation with CSS Variables: A Systematic Method

Question

Can we mimic the functionality of Sass's darken() function using CSS variables to generate shades of a defined color?

Approach Using Relative Color Syntax

CSS introduces "relative color syntax," which enables the following:

:root {
  --color-primary: #f00;
  --color-primary-darker: hsl(from var(--color-primary) h s calc(l - 5));
  --color-primary-darkest: hsl(from var(--color-primary) h s calc(l - 10));
}

Here's how it works:

  • --color-primary: Define the base color.
  • --color-primary-darker: Darken the base color by 5% using hsl().
  • --color-primary-darkest: Darken the base color by 10% using hsl().

Usage

Use these variables to style elements:

.button {
  background: var(--color-primary);
}

.button:hover,
.button:focus {
  background: var(--color-primary-darker);
}

.button:active {
  background: var(--color-primary-darkest);
}

This approach allows you to define color shades dynamically without modifying the color variable, achieving the desired gradient effect with three shades.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3