Mixing colors with CSS
I’m working on a UI library for people who love HTML, powered by modern CSS and Web Components.
Unlike previous projects of mine, I’m not using Sass at all. I want the whole thing to work with plain old vanilla CSS.
One of my favorite things I used to use Sass for was darkening or lightening a color to get the :hover color. I gave that up when I switched to a build-free process.
Or did I?
Last week, I learned about the color-mix() CSS function. As the name implies, it lets you mix two colors together.
For example, let’s say my button elements had a background-color of #0088cc. I could use the color-mix() function to add a little black to the color to darken it up a bit.
button {
background-color: #0088cc;
color: #ffffff;
}
button:hover {
background-color: color-mix(in oklab, #0088cc, #000000 20%);
}The color-mix() function accepts three arguments:
- The
color-interpolation-methodto use. For our purposes, we generally wantin oklab(though I’ll confess the theory and math on this kind of thing is beyond me). - The base color.
- The color to mix into it.
Both the base color and color to mix in support a percentage, the amount of that color to use.
If only one color has a percentage, the other color uses 100% minus that percentage as its value. If neither has a percentage, 50% is used for each. If the two add up to more than 100%, the it uses some math to normalize the two values.
The color-mix() function hit baseline in 2023, and currently has support in about 92% of browsers globally.