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
Release: 2025-01-03 03:22:38
Original
892 people have browsed it

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;
}
Copy after login

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));
Copy after login

Similarly, to darken the primary color by 10%:

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

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template