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

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

Mary-Kate Olsen
Release: 2024-12-13 03:31:09
Original
352 people have browsed it

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

Creating Color Shades with CSS Variables: Simulating Sass's Darken() Function

Problem Statement:

Creating dynamic color shades for hover, focus, and active states using CSS variables in a manner similar to Sass's darken() function.

Solution:

The CSS Color Module Level 4 Specification introduces "relative color syntax," which enables the manipulation of colors using arithmetic operations. This allows for the creation of color shades as follows:

:root {
  --color-primary: #f00; /* any format you want here */
  --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));
}

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

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

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

In this code:

  • var(--color-primary) is the original color.
  • --color-primary-darker is 5% darker than --color-primary.
  • --color-primary-darkest is 10% darker than --color-primary.

By adjusting the percentages in the calc() expression, you can generate various shades of the base color. This approach provides similar functionality to Sass's darken() function, but using purely CSS syntax.

The above is the detailed content of How Can I Create CSS Color Shades Like Sass's `darken()` Function Using Only CSS Variables?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template