Calculating Color: Dynamic Theming with CSS Variables
|
|
|
Una showed us how to create dynamic color themes with simple CSS!
|
CSS Variables
|
Una gave a brief overview of a few CSS variables including currentColor and @property but ultimately focused on --var()
|
Una demonstrated how breaking hsl (hue, saturation, and lightness) color values into separate variables can allow us to create dynamic color palettes.
|
Start with a brand color
|
--colorBrand: hsl(265, 100%, 47%);
|
Break that brand color into separate parts
|
Notice the -h, -s, and -l respectively.
|
--colorBrand-h: 265;
--colorBrand-s: 100%;
--colorBrand-l: 47%;
|
Define a dynamic brand color using your variables
|
--colorBrand: hsl(var(--colorBrand-h), var(--colorBrand-s), var(--colorBrand-l));
|
Create variations
|
With a dynamic brand color defined, you can use color theory to create variations of that color for different uses such as:
|
- buttons
- card accents
- light and dark modes
- and even browser art
|
Take a look at the complementary and triadic variations in this codepen for inspiration.
|
Make it accessible
|
Dynamic color theming can have accessibility benefits as well. By creating a contrast threshold, we can look at the luminosity (the "L" in hsl) of our brand color and set the text color accordingly.
|
:root {
--contrastThreshold: 45%
}
|
.element {
--switchContrast: calc((var(--colorBrand-l) - var(--contrastThreshold)) * -100);
color: hsl(0, 0%, var(--switchContrast));
}
|
Browser support
|
|