Mixing Colors with CSS
Photo Credit: Pawel Czerwinski
How cool is it that we can now take two colors and mix them together in CSS?
If you aren’t familiar with what I’m referring to, I’m talking about the new CSS color-mix()
function. It is surprisingly straightforward to use and can provide some great results.
color-mix()
Function
The color-mix()
function takes in a couple of parameters: the color space you want to use and the colors you want to mix.
A very basic example looks like this:
.box {
background: color-mix(
in hsl,
#FF0000,
#0000FF
);
}
This will use the hsl
color space to mix red (#FF0000
) and blue (#0000FF
) to make a purple color.
You can do more with it though! We can tell it how much of each color we want to mix in percentages:
.box {
background: color-mix(
in hsl,
#FF0000 25%,
#0000FF 50%
);
}
The hsl
color space even provides further control using hue interpolation where we can adjust the hue to give different results:
.box1 {
background: color-mix(
in hsl shorter hue,
#FF0000,
#0000FF
);
}
.box1 {
background: color-mix(
in hsl longer hue,
#FF0000,
#0000FF
);
}
Color Spaces
I can’t honestly say I understand color spaces, however, from what I understand, the CSS Color Module Level 4 has introduced several high-definition color spaces. The main thing to grok from this is that HD color spaces provide even more color options than non-HD color spaces.
Adam Argyle has a full write-up on color spaces if you want to understand the technical side of things a bit more.
My point is, with color-mix()
, you aren’t limited to using just the hsl
color space. You can use many of the supported color spaces in CSS (including the new CSS Color Level Module 4’s HD color spaces), such as:
hsl
hwb
lab
lch
oklab
oklch
srgb
Demonstration
Here is a small demo using color-mix
to provide various shades of a single color by mixing a brand color with the selected white and black colors:
See the Pen CSS color-mix() Demo by Ryan Trimble (@mrtrimble) on CodePen.
I added some JavaScript here as well to demonstrate how this is all handled in the browser. Simply changing the color of the --_brand-color
custom property affects the colors throughout the entire layout. Amazing!
Browser Support
The awesome news here is that color-mix()
and the new color spaces are supported in all major browsers!
Closing Thoughts
I feel like this is an awesome addition to CSS as a whole. Pairing CSS custom properties with the color-mix
function will be super helpful for customizing themes or applying different colors to states such as :active
, :hover
, and :focus
.
For more information on color-mix()
or CSS color spaces, check out these resources: