Color Creativity With CSS Color-Mix
Published: 2024-03-06 16:18:35

by [Kelvin Okuroemi](https://blog.openreplay.com/authors/kelvin-okuroemi)


<blockquote><em>
The new CSS `color-mix` function empowers us with precise control over color blending, enabling us to choose the colors, modes, models, and proportions, and this article will explore how to wield this powerful tool to enhance your web design and development projects.
</em></blockquote>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>



Hello, fellow CSS enthusiasts! Have you ever found yourself in a situation where you needed a slightly different shade of color in CSS and had to switch back and forth between hex codes and values you don't really understand? You're certainly not alone. Whether you're a designer, a front-end developer, or simply someone who enjoys playing with colors, this article is tailor-made for you.

Now, there's a more convenient and efficient way to achieve the colors you desire with minimal code, supported in all modern browser versions. Enter the `color-mix` property, a valuable addition to your colorful toolkit. (This property enjoys full support and stability in all major web browsers.) 

Below is the fundamental syntax for the `color-mix` property, but don't worry, I'll provide context shortly:

**NOTE**: *Code pens are available in the "resources" section to practice all the examples on the go.*

```css
 color-mix(color-mode, color percentage , color percentage);
```
- The `color-mode` and `color` parameters are mandatory, while the `percentage` is optional.


## Color models
When you ask people to name colors, the usual responses are red, green, purple, and so on. This perception is not incorrect, as humans have three photopigments that primarily perceive three colors: red, green, and blue, or combinations of these three. However, computers and web browsers employ alternative methods for creating colors.

These colors can be generated as models or modes, also known as color spaces. [Color models](https://www.wigglepixel.nl/en/blog/what-are-color-models/) are not intricate or mysterious concepts but systems scientists use to represent colors mathematically. This representation enables easy naming and recreation of colors in various contexts, such as web development.

There is a plethora of color models available, but developers frequently work with the following popular ones:
- [Red, Green, Blue (RGB)](https://en.wikipedia.org/wiki/RGB_color_model)
- [Hue, Saturation, Value (HSV)](https://en.wikipedia.org/wiki/HSL_and_HSV), which is a variant of RGB.
- [Hue, Saturation, Lightness (HSL)](https://en.wikipedia.org/wiki/HSL_and_HSV), another RGB variant.
- [Cyan, Magenta, Yellow, Black (CMYK)](https://en.wikipedia.org/wiki/CMYK_color_model)


Let's look at each briefly.

### RGB
RGB is the most prevalent method for defining colors on computer screens. It operates by combining three primary colors, red, blue, and green, represented by sets of three numerical values.

For example, a value of (0, 255, 0) signifies green, as it exclusively includes green in the combination.

On the other hand, (0, 0, 0) corresponds to black because none of the colors are present, and (255, 255, 255) results in pure white.

### HSV
HSV, a variation of the RGB color model, provides a more intuitive way of understanding colors. It comprises three essential dimensions: hue, saturation, and value.

- **Hue** represents the angle of the color on the RGB color circle.
- **Saturation** dictates the amount of color used.
- **Value** controls the brightness of the color.

These dimensions are interconnected, meaning that setting a value to 0% results in zero brightness, rendering the color invisible.

### HSL
HSL is another iteration of the RGB color model, but it replaces the value dimension with lightness. Here's a breakdown of its components:

- **Hue** still signifies the color's angle on the RGB color circle.
- **Saturation** continues to regulate the amount of color.
- **Lightness** takes charge of luminosity instead.

Both HSL and HSV can be mathematically represented as cylindrical color models.

### CMYK
This color model is primarily employed in the realm of printing. It combines four key colors: Cyan, Magenta, Yellow, and Black (CMYK). It reveals the quantity of these four colors present in any given color.

The combination is expressed using four percentages. For instance, a color like (0%, 100%, 0%, 0%) represents magenta, signifying the presence of 100% magenta and the absence of other colors.

## Color modes
[Color modes](https://www.interaction-design.org/literature/topics/color-modes#:~:text=Color%20modes%20are%20the%20settings,across%20media%20for%20brand%20consistency.) are a vital concept in the world of color creation. They represent practical implementations of color models, offering a more intuitive way to comprehend the color combinations derived from these models.

Color modes can be viewed as an evolution of color models. Without them, screens wouldn't be capable of displaying the vast spectrum of millions of color combinations we're accustomed to.

In essence, color modes serve as advanced representations of colors, each offering varying levels of detail. Different color modes yield distinct levels of color intricacy.

Here are some examples of popular color modes:

- RGB mode: Resulting in millions of colors
- CMYK mode: Producing four printed colors
- [Index mode](https://en.wikipedia.org/wiki/Indexed_color): Providing 256 colors
- [Grayscale mode](https://en.wikipedia.org/wiki/Grayscale)
- [Bitmap mode](https://www.graphic-design-employment.com/just-what-is-a-bitmap.html)
- [Lab mode](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lab)
- [Oklab mode](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklab)

These modes empower designers, artists, and developers with the tools to create and work with diverse colors, catering to specific needs and contexts.

## Color-mix basics
To grasp the syntax of the `color-mix` property, you need to see it in action, applied to style elements. Let's illustrate this with an example.

1. Create a simple HTML file, `color-mix-basics.html`.
```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Color-mix example</title>
    <link rel="stylesheet" href="color-mix-basics.css" />
  </head>
  <body>
    <div class="colors">
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>
</html>
```
* A `div` container with three child `div` elements.

2. Create a CSS file for styling, `color-mix-basics.css`.
```css
html {
  color-scheme: dark;
}

.colors {
  display: flex;
  height: 90vh;
  position: relative;
}

.colors > * {
  flex: 1 1 100%;
}

:root {
  --base: purple;
}
```
- The `html` element establishes the website's color scheme as dark, which means the default background color will be dark.
- The `.colors` selector styles all the `div` elements.
- `colors > *` targets all immediate children of elements with the `.colors` class.
- `:root { --base: purple; }` sets a CSS custom property at the highest level of the document. `:root` refers to the top-level element in the HTML document. This rule defines a custom property named `--base` and assigns it a default value of `purple`.
 
3. Now, use the color-mix property.
```css
.colors > :nth-of-type(1) {
  background-color: color-mix(in oklab, var(--base), white);
}

.colors > :nth-of-type(2) {
  background-color: var(--base);
}

.colors > :nth-of-type(3) {
  background-color: color-mix(in oklab, var(--base), black);
}
```
- The fundamental syntax of `color-mix` requires specifying the color mode you intend to use for color manipulation. In this case, you're using the `oklab` mode and indicating the colors you want to blend.
- On the first child of `.colors` (`.colors > :nth-of-type(1)`), the `color-mix` property offers the capability to modify the color purple by mixing the `--base` color, `purple`, with `white`. This blending occurs within the `oklab` color mode.
- Moving on to the second child (`.colors > :nth-of-type(2)`), there's no color mixing involved. Instead, the background color is set using the `--base` color, `purple`.
- Finally, for the last child (`.colors > :nth-of-type(3)`), the same color mixing technique is applied with the `color-mix` property, but this time, it's mixing the `--base` color with `black`.
- Notice in the image below a graduation of different shades of purple:

![BasicResult.gif.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image1.gif)


Now try changing the `--base` color to red, and check out the result, and still observe how the red colors share a slow graduation between shades of red:

![redResult.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image2.gif)

[Click here](https://codepen.io/kelvinokuroemi/pen/xxBpbdy) to get a playground to experiment with the code in this section.


## Advanced techniques with color-mix
Using the standard syntax for color mixing, such as `color-mix(in oklab, var(--base), white);`, the colors are mixed in equal proportions, typically at 50% each. However, the CSS `color-mix` property offers a range of options for achieving precise color combinations.

You can mix colors with varying percentages, utilize different modes, and even adjust the color direction to achieve the exact colors you desire. This flexibility allows for more tailored and nuanced color blending in your web development projects.
### Utilizing Different Percentages
To illustrate the operation of color percentages, we'll experiment with various percentages to demonstrate how even small adjustments can be effectively employed with the color-mix property.

1. Change `color-mix-basics.css` to the code below:
```css
html {
  color-scheme: dark;
}

.colors {
  display: flex;
  height: 90vh;
  position: relative;
  gap: 2px;
}

.colors > * {
  flex: 1 1 100%;
}

.colors > :nth-of-type(1) {
  background-color: color-mix(in oklab, red 66.6%, blue 33.33%);
}

.colors > :nth-of-type(2) {
  background-color: color-mix(in oklab, red 100%, blue 50%);
}

.colors > :nth-of-type(3) {
  background-color: color-mix(in oklab, red, blue);
}
```
- While still utilizing the `oklab` color mode, we blend two color values, `red` and `blue`, using different percentages.
- Even when no specific percentages are provided, like for `.colors > :nth-of-type(3)`, the `color-mix` property defaults to mixing the two colors in equal proportions, with both colors set at 50% each.
- If you're wondering why the values for the second `div` element are set to `red 100%, blue 50%`, it's important to note that this is an intentional error. When color values exceed 100%, the `color-mix` property automatically scales them down to ensure they add up to 100%. The browser normalizes the values in this way. 
- For the second child `div`, the red color might be scaled down to 66.7%, and the blue color might be scaled down to 33.33%, ensuring that the total remains 100%. 
- Observe that this results in a 2:1 ratio in the image below, with red occupying two-thirds and blue taking one-third. As a result, the second `div` displays the same color as the first.

![basicPercentage.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image3.gif)

[Click here](https://codepen.io/kelvinokuroemi/pen/WNmdbER) to get a playground to experiment with the code in this section.


### Color Scheme with Percentages
Moving on, let's experiment with creating a mock color scheme. Try playing around with different percentages to explore how the `color-mix` property can be used to craft unique and customizable color schemes.
1. Using `color-mix-basics.html`, make changes to have nine `div` elements. If you are using the code pen, make changes to the HTML so it can have nine `div` elements.
```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mock color scheme</title>
    <link rel="stylesheet" href="mock-color-scheme.css" />
  </head>
  <body>
    <div class="colors">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>
</html>
```

2. Likewise, make changes to `color-mix-basics.css`.
```css
html {
  color-scheme: dark;
}

.colors {
  display: flex;
  height: 90vh;
  position: relative;
}

:root {
  --base: purple;
}

.colors > * {
  flex: 1 1 100%;
}

.colors > :nth-of-type(1) {
  background-color: color-mix(in oklab, var(--base) 10%, white);
}

.colors > :nth-of-type(2) {
  background-color: color-mix(in oklab, var(--base) 30%, white);
}

.colors > :nth-of-type(3) {
  background-color: color-mix(in oklab, var(--base) 50%, white);
}

.colors > :nth-of-type(4) {
  background-color: color-mix(in oklab, var(--base) 70%, white);
}

.colors > :nth-of-type(5) {
  background: var(--base);
}

.colors > :nth-of-type(6) {
  background-color: color-mix(in oklab, var(--base) 70%, black);
}

.colors > :nth-of-type(7) {
  background-color: color-mix(in oklab, var(--base) 50%, black);
}

.colors > :nth-of-type(8) {
  background-color: color-mix(in oklab, var(--base) 30%, black);
}

.colors > :nth-of-type(9) {
  background-color: color-mix(in oklab, var(--base) 10%, black);
}
```
* Tinker around with the percentages to see the differences and changes, just as we have a very slow graduation in the intensity of the colors shown in the image below:

![mockColorScheme.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image4.gif)

[Click here](https://codepen.io/kelvinokuroemi/pen/vYPpEJo) to get a playground to experiment with the code in this section.



### Experimenting with Different Directions
In a [color wheel](https://www.britannica.com/science/color-wheel), there's a sequence of colors, and when you want to blend different colors on this wheel, you have the option to choose the direction in which the colors will mix. There are two possibilities: the long direction and the short direction.


A color palette representing the color wheel is shown below to visualize the long and short directions of colors:

![preview.jpg](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image5.jpg)


For instance, consider a hypothetical progression of colors on a color wheel: purple, blue, black, red, orange, yellow, pink, pink, and peach.

Now, if you aim to blend black and orange in the short direction, the color combination will be straightforward—black, red, and orange—because that's the quickest connection between these two colors.

However, when mixing black and orange in the long direction, the color combination takes a longer route, traveling backward through the wheel. In this case, the combination would include black, blue, purple, peach, pink, yellow, orange, red, and black. You get the idea, right?

It's important to note that this feature isn't available in every color model but is specific to cylindrical color models and modes such as HSV, HSL, HWB, and LCH. These models and modes use degrees as units, and you need to specify the `hue` keyword to use this directional mixing.

Syntax for creating colors with color-mix using directions:
```css
background-color: color-mix(in lch longer hue, var(--color-1), var(--color-2));
```
- To start, we use the `in lch longer hue` syntax to specify the color mode. Remember that this mode must be a cylindrical one. We select the direction as `longer`, and specifying the `hue` keyword is crucial.

Let's replicate this color effect using the `color-mix` property.

1. Make these changes to `color-mix-basics.html`. 
```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mock color scheme</title>
    <link rel="stylesheet" href="color-mix-basics.css" />
  </head>
  <body>
    <div class="colors">
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>
</html>

```
* Reduce the child `div` elements of the `.colors`  `div` to three.

2. Also make changes to the `color-mix-basics.css`.
```css
:root {
  --color-1: purple;
  --color-2: cyan;
}

html {
  color-scheme: dark;
}

.colors {
  display: flex;
  height: 90vh;
  position: relative;
}

.colors > * {
  flex: 1 1 100%;
}
```
* Apart from styling the elements, we will use two base color values, `purple` and `cyan`.

3. Now, this is how to specify directions with color-mix.
```css
.colors > :nth-of-type(1) {
  background-color: color-mix(
    in lch longer hue,
    var(--color-1),
    var(--color-2)
  );
}

.colors > :nth-of-type(2) {
  background-color: color-mix(
    in lch shorter hue,
    var(--color-1),
    var(--color-2)
  );
}

.colors > :nth-of-type(3) {
  background-color: var(--color-2);
}
```
Notice in the image below the first two child `div` elements within the `.colors` element; you'll notice that the colors are distinct, even though they start from the same base. As you've correctly guessed, the key differentiator here is the direction: `longer` or `shorter`. :

![Directions.gif.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image6.gif)


Don't hesitate to tweak the color modes, directions, and colors to see different effects.

[Click here](https://codepen.io/kelvinokuroemi/pen/KKEZwXq) to get a playground to experiment with the code in this section.

### Leveraging Various Color Modes
As mentioned earlier, CSS offers a wide range of color modes. While popular models like HSL, RGB, and CMYK are commonly used for visual color representation, CSS introduces newer color modes like LAB, HWB, and OKLAB. OKLAB, in particular, is gaining popularity thanks to innovative CSS features like color-mix.

While it may seem overwhelming to understand the intricate details of how these models combine colors, having a basic grasp of how color combinations are represented in various color modes can be a valuable front-end tool. Why? Because different colors can be rendered differently with different color modes, you wouldn't want to mix colors to achieve a specific result only to end up with something entirely different.

By having a basic understanding of color modes, you can switch between them when necessary. This flexibility ensures you can achieve the desired color results without surprises.

Now, let's make a beautiful palette using six different color modes: OKLAB, OKLCH, sRGB, linear-sRGB, HWB, and XYZ.

1. Create an HTML playground, `color-mode-demo.html.`
```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="color-mix-with-different-modes.css" />
    <title>Color modes</title>
  </head>
  <body>
    <div class="colors oklab">
      <span class="color-mode">oklab</span>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    <div class="colors oklch">
      <span class="color-mode">oklch</span>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    <div class="colors srgb">
      <span class="color-mode">srgb</span>

      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    <div class="colors linear-srgb">
      <span class="color-mode">srgb-linear</span>

      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    <div class="colors hwb">
      <span class="color-mode">hwb</span>

      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    <div class="colors xyz">
      <span class="color-mode">xyz</span>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>
</html>
```
- There are six primary `div` elements in the context we're exploring. Each of these `div` elements is assigned two classes for styling to signify which color mode will be employed. For instance, you'll encounter elements like `<div class="colors oklab">`, which utilize both classes for their respective styling and color mode indications.


2. Create a CSS demo, `color-mode-demo.css`, and add the code below.
```css
:root {
  --base: hsl(61, 90%, 55%);
}

html {
  color-scheme: dark;
}

.colors {
  display: flex;
  height: 15vh;
  position: relative;
}

.colors > * {
  flex: 1 1 100%;
}

.color-mode {
  position: absolute;
  width: max-content;
  height: min-content;
  margin: auto;
  inset: 0;
  text-align: center;
  background: white;
  color: black;
}
```
- This example's primary color is `hsl(61, 90%, 55%)`.
- The color scheme is also specified with the rule `html { color-scheme: dark; }`.
- Styling is applied to elements with the classes `.colors` and `.color-mode`, and the children of elements with the class `.colors` receive styling as well; this is just to specify which color mode `div` is for which result, hence the white buttons in the image below:

![DemoOne.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image7.gif)


3. Continuing with `color-mode-demo.css,` add more CSS styling.
```css
.oklab {
  --color-mode: oklab;
}
.oklch {
  --color-mode: oklch;
}
.srgb {
  --color-mode: srgb;
}
.linear-srgb {
  --color-mode: srgb-linear;
}
.hwb {
  --color-mode: hwb;
}
.xyz {
  --color-mode: xyz;
}
```
- In this context, we're defining CSS variables using the `--color-mode` variable. The concept here is that for each class selector, the CSS variable holds a color mode specific to that particular class selector.
- For instance, in the following line of code: `.oklab { --color-mode: oklab; }`, `.oklab` represents the class selector, and every element to which this class selector is applied will utilize the OKLAB color mode, as specified by `--color-mode: oklab`.
4. Then, use color-mix to create colors.
```css
.colors > :nth-of-type(1) {
  background-color: color-mix(
    in var(--color-mode),
    var(--base) 10%,
    rgb(255, 255, 255)
  );
}

.colors > :nth-of-type(2) {
  background-color: color-mix(in var(--color-mode), var(--base) 30%, white);
}

.colors > :nth-of-type(3) {
  background-color: color-mix(in var(--color-mode), var(--base) 50%, white);
}

.colors > :nth-of-type(4) {
  background-color: color-mix(in var(--color-mode), var(--base) 70%, white);
}

.colors > :nth-of-type(5) {
  background: var(--base);
}

.colors > :nth-of-type(6) {
  background-color: color-mix(in var(--color-mode), var(--base) 70%, black);
}

.colors > :nth-of-type(7) {
  background-color: color-mix(in var(--color-mode), var(--base) 50%, black);
}

.colors > :nth-of-type(8) {
  background-color: color-mix(in var(--color-mode), var(--base) 30%, black);
}

.colors > :nth-of-type(9) {
  background-color: color-mix(in var(--color-mode), var(--base) 10%, black);
}
```
- In this section, the `color-mix` property is employed to define the background colors for each of the child `div` elements within the `.colors` element. The syntax remains consistent, considering that CSS variables specified earlier are utilized in this context.
- If you find it puzzling why the base color is in HSL, specifically `hsl(61, 90%, 55%)`, and it's being mixed with more standard colors like `black`, or why various color modes are involved, it's important to note that the CSS `color-mix` property allows for the mixing of colors in different color modes. 
- Take note of how the representation of colors varies in the image below when you switch between different color modes, even when working with the same base color:

![DemoTwo.gif](https://blog.openreplay.com/images/color-creativity-with-css-color-mix/images/image8.gif)

Additionally, pay attention to any similarities you may uncover among the outcomes of specific color modes.

This flexibility with different color modes allows for versatile and intricate color blending, resulting in unique and eye-catching visual effects even when using the same color.

[Click here](https://codepen.io/kelvinokuroemi/pen/zYbpxPL) to get a playground to experiment with the code in this section.


## Conclusion
The world of web development and design is becoming more vibrant and dynamic than ever, thanks to powerful new properties like `color-mix.`
This versatile tool empowers designers, developers, and color enthusiasts to create captivating and unique color schemes with remarkable ease.

Throughout this journey, we've covered the fundamentals, delved into the intricacies of color models, and explored the significance of color modes.

You've learned the basics of the `color-mix` property, allowing you to blend colors, adjust proportions, and choose modes to craft the perfect palette for your projects.

We've also ventured into advanced techniques, showing you how to fine-tune color percentages, experiment with different color modes, and even control the direction in which colors are mixed.

With this knowledge, you now have the creative tools to bring your color visions to life, whether designing a stunning website, creating an engaging user interface, or adding a unique touch to your digital creations.

Feel free to explore because your digital masterpieces are waiting to come to life in a spectrum of brilliance.

## Resources to read more
* [Color modes vs. Color models](https://www.tobiamontanari.com/color-model-vs-color-space-a-beginners-guide/)
* [Color modes and models in programming](https://programmingdesignsystems.com/color/color-models-and-color-spaces/index.html)