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); }
In this code:
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!