Course contentsShow
← Web Development
Lesson 483 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

color-mix() for Dynamic Color Blending

Blend two colors in a specified color space to create harmonious palettes and state variations.

color-mix() for Dynamic Color Blending

What you'll learn: How to blend two colors together programmatically to create dynamic, harmonious color variations without hardcoding multiple shades.

The Core Idea

color-mix() is a CSS function that takes two colors and mixes them in a specified color space, like mixing paint on a palette. Instead of manually calculating lighter or darker versions of your brand color, you can let the browser blend them mathematically, creating consistent hover states, disabled styles, or theme variations.

Think of it like making a smoothie: you choose two ingredients (colors), decide how much of each to use (percentages), and pick a blender setting (color space) that determines how they combine.

Basic Syntax

color-mix(in <color-space>, <color1> <percentage>, <color2> <percentage>)

Practical Examples

:root {
  --primary: #3b82f6;
  --white: #ffffff;
}

.button {
  background: var(--primary);
  
  /* Lighten on hover by mixing 20% white */
  &:hover {
    background: color-mix(in srgb, var(--primary) 80%, var(--white) 20%);
  }
  
  /* Disabled state: mix with gray */
  &:disabled {
    background: color-mix(in srgb, var(--primary), gray 50%);
  }
}

/* Dark mode variants */
.alert {
  --alert-red: #ef4444;
  
  /* Soften the red by mixing with current background */
  background: color-mix(in srgb, var(--alert-red) 15%, transparent);
}

The percentages are optional; if you omit them, the browser assumes a 50/50 mix. Different color spaces (srgb, hsl, lch) produce different visual results, with lch often providing the most perceptually uniform blending.

Key Takeaway: color-mix() enables dynamic color blending directly in CSS, eliminating the need for preprocessor functions or multiple manually-created color variants while ensuring mathematical consistency across your color system.