Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Mixing colors to create variants in CSS

If you go to paint shops and show them a color that you want to buy and they don’t have the exact color, they will mix different colors to create the same color you want. This is how they create variants of colors.

You can do the same in CSS as well. You can mix two colors to create variants of colors. This can be done using the color-mix() function in CSS.

So, let’s say you have the following colors defined in the root that you’ve already been using in your CSS.

:root {
  --primary: #e131ff;
  --secondary: #1b2569;
}

But now you want to create a color variant that’s the amalgamation of these two colors. You can do that using the color-mix() function like so.

.post {
  background-color: color-mix(in srgb, var(--primary), var(--secondary));
}

This will create a color that’s a mix of --primary and --secondary colors.

The in srgb part is the color space in which the color will be mixed. You can also use in lch or in hsl which are LCH (Lightness, Chroma, Hue) and HSL (Hue, Saturation, Lightness) color spaces respectively.

By default, the color-mix() function will mix the colors in the same proportion. Meaning, both colors will be mixed in a ratio of 50:50.

But you can also specify the proportion of the colors you want to mix in percentages like so.

.post {
  background-color: color-mix(in srgb, var(--primary) 70%, var(--secondary));
}

This will mix --primary and --secondary colors in the ratio of 70:30.

Based on what color space you’re using, the color-mix() function will mix the colors accordingly. For instance, if you’re using the in lch color space, the colors will be mixed in the LCH color space. If you’re using in srgb, the colors will be mixed in the sRGB color space.

So, the produced colors will be slightly different based on the color space you’re using.

Here’s a CodePen that shows color variants created using the sRGB color space.

See the Pen Understanding colo-mix() function (srgb) by Amit Merchant (@amit_merchant) on CodePen.

And the same thing using the LCH color space.

See the Pen Understanding colo-mix() function (srgb) by Amit Merchant (@amit_merchant) on CodePen.

As you can tell, with the help of the color-mix() function, it’s pretty easy if you want to create color palettes for your website. You can just define a few colors in the root and then create variants of those colors using the color-mix() function.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?