tezvyn:

color-mix(): CSS's Native Color Blender

AI-drafted, machine-checkedSource: w3.orgintermediate
color-mix(): CSS's Native Color Blender

color-mix() lets you blend two colors directly in CSS, like mixing paint. Use it to generate theme variations, like hover states, from a base color. The chosen color space (e.g., srgb, oklch) dramatically changes the result, so always specify it.

WHY IT EXISTS: Before color-mix(), creating variations of a base color, like a slightly lighter blue for a hover state, required CSS preprocessors like Sass or hardcoding multiple color values. This made dynamic theming difficult and tied styling logic to build tools. color-mix() brings this capability directly into the browser, enabling more flexible and maintainable design systems.

THE MENTAL MODEL: Think of color-mix() as a digital paint mixer. You provide two colors and specify the proportion of each. For example, "take this primary blue, mix in 20% white, and give me the result." The key difference from physical paint is that you also choose the "mixing room"—the color space—which fundamentally affects how the colors combine.

HOW IT WORKS: The function syntax is color-mix(in <colorspace>, <color1> <percentage?>, <color2> <percentage?>). For example, color-mix(in srgb, blue, white 30%) means "mix blue and white in the srgb color space, with the final color being 30% white and, by implication, 70% blue." If no percentages are given, it defaults to a 50/50 mix. If only one percentage is given, the other is inferred. The default color space if unspecified is oklab.

WHEN TO USE IT: Use color-mix() for creating systematic color palettes in a design system. It's perfect for generating interactive states (hover, active, focus) from a single source color. It's also useful for creating tints (mixing with white), shades (mixing with black), and tones (mixing with gray) on the fly, directly in your CSS.

WHEN NOT TO USE IT: Avoid color-mix() if you need to support older browsers, as it's a modern CSS feature. For complex color manipulations beyond simple blending, dedicated color libraries might still be more powerful. It's for deriving colors from existing ones, not for generating complex palettes from mathematical principles.

ONE CANONICAL EXAMPLE: To create a UI theme, you can define a single brand color and derive all variants. For instance: --brand-blue: #007bff; --button-bg: var(--brand-blue); --button-hover-bg: color-mix(in oklch, var(--brand-blue), white 15%); --button-disabled-bg: color-mix(in oklch, var(--brand-blue), gray 40%);. This makes the entire theme responsive to a single change in the brand color variable.

Read the original → w3.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.