CSS Color Tricks
Written
- Author: Una Kravetz
- Source: https://www.youtube.com/watch?v=VD108ccVDSY
- You can get a lot of flexibliity in color management by breaking HSL colors into a single CSS variable for each of H, S, and L.
- Lightening and Darkening
- Simple effects just use
calc
to alter one or more attributes. hsl( var(--color-h), var(--color-s), calc(var(--color-l) + var(--lighten-factor)) )
- Simple effects just use
- Blending Colors
- Create a new color where each of H, S, and L is the average of the attribute from the two colors.
hsl( calc((var(--color1-h) + var(--color2-h)) / 2), calc((var(--color1-s) + var(--color2-s)) / 2), calc((var(--color1-l) + var(--color2-l)) / 2), )
- Contrasting Text Color
- This is a relatively simple hack but enough for a lot of cases.
- Take the luminance of the background color and tweak it to get black or white.
--contrastThreshold: 60%; --switch: calc((var(--color-l) - var(--contrastThreshold)) * -100); color: hsl(0, 0,var(--switch));
Thanks for reading! If you have any questions or comments, please send me a note on Twitter. And if you enjoyed this, I also have a newsletter where I send out interesting things I read and the occasional nature photo.