Home >Web Front-end >CSS Tutorial >How Can I Generate CSS Color Shades Using Variables Like Sass's `darken()` Function?

How Can I Generate CSS Color Shades Using Variables Like Sass's `darken()` Function?

DDD
DDDOriginal
2025-01-03 03:22:38893browse

How Can I Generate CSS Color Shades Using Variables Like Sass's `darken()` Function?

Using CSS Variables to Create Color Shades (Like Sass's darken() Function)

In CSS, it's possible to define a primary color variable and automatically generate shades for hover, focus, and active states. Here's how:

Defining the Primary Color Variable:

:root {
  --color-primary: #f00;
}

Using Relative Color Syntax to Darken the Primary Color:

The CSS Specification introduces "relative color syntax," which allows us to manipulate colors using equations. To darken the primary color by 5%:

--color-primary-darker: hsl(from var(--color-primary) h s calc(l - 5));

Similarly, to darken the primary color by 10%:

--color-primary-darkest: hsl(from var(--color-primary) h s calc(l - 10));

Applying the Color Shades:

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

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

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

By defining the primary color as a variable, we can now easily modify it and automatically generate shades for various states. This approach provides a more maintainable and efficient way to create color variations compared to using separate color classes.

The above is the detailed content of How Can I Generate CSS Color Shades Using Variables Like Sass's `darken()` Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn