color-mix() Function
Overview
Historically, if you had a brand color (#0055ff) and you wanted to create a semi-transparent version or a slightly darker version for a hover state, you had to manually calculate a brand new hex code, or use a heavy preprocessor like Sass (darken($color, 10%)). Native CSS now features color-mix(), an incredibly powerful native function that blends two colors together directly in the browser.
Syntax
/* The Syntax: color-mix(in [color-space], color1 percentage, color2 percentage) */
.card {
/* Mix 80% Blue with 20% White (Creates a perfect pastel tint!) */
background: color-mix(in srgb, blue 80%, white);
}
.overlay {
/* Mix 50% Black with 50% Transparent (Creates a perfect backdrop dim!) */
background: color-mix(in srgb, black 50%, transparent);
}
/* Mixing with CSS Variables (The real superpower) */
:root {
--brand: #ff5500;
}
.btn:hover {
/* Darken the brand color dynamically on hover! */
background: color-mix(in oklch, var(--brand) 80%, black);
}Common Pitfalls
Omitting the
in [color-space]declaration. You must explicitly tell the browser which mathematical model to use when blending the colors (in srgb,in oklch,in hsl).Using
in srgbfor mixing highly saturated colors. In the sRGB color space, mixing Blue and Blue notoriously creates a muddy, ugly gray/brown in the middle. If you mixin oklch, it passes through vibrant, beautiful purples and greens instead.
Interview Questions
How does color-mix() replace the need for Sass/SCSS color functions?
Because color-mix() runs natively in the browser, it can mix dynamic CSS Custom Properties (var(--theme-color)), which change at runtime (e.g., when toggling Dark Mode). Preprocessors compile on the server and cannot do this.
Real-World Example
Generating an entire UI color palette from a single CSS variable.
:root {
--primary: #4f46e5;
/* Generating states entirely natively! */
--primary-hover: color-mix(in oklch, var(--primary) 85%, black);
--primary-active: color-mix(in oklch, var(--primary) 70%, black);
/* Generating a super-light background tint for alerts */
--primary-bg: color-mix(in oklch, var(--primary) 10%, white);
}Check Your Knowledge
Test your understanding of color-mix() Function with these quick questions.