Sub topic 3
Deriving Colors with Relative Color Syntax
Assume you know CSS selectors, custom properties, and hex, rgb(), and hsl(). This chapter uses oklch() and color-mix() to derive related colors without repeating base values.
Deriving colors from a base
Relative color syntax creates a new color from an existing one. The from clause exposes the source color's channels. In OKLCH, l is lightness, c is chroma, and h is hue.
:root {
--brand: oklch(62% 0.19 255);
}
.button {
background: oklch(from var(--brand) calc(l - 0.1) c h);
border-color: oklch(from var(--brand) l c h / 0.4);
}The button background is darker because its lightness is reduced. Its chroma and hue stay unchanged. The border keeps all three channels but has 40% opacity.
Hue interpolation
When color-mix() combines colors, it must choose a path between their hues on the color wheel. Use a hue method when the path matters.
.swatch-a {
background: color-mix(in oklch shorter hue, red, blue);
}
.swatch-b {
background: color-mix(in oklch longer hue, red, blue);
}
.swatch-c {
background: color-mix(in oklch increasing hue, red, blue);
}
.swatch-d {
background: color-mix(in oklch decreasing hue, red, blue);
}shorter hue uses the smaller angular distance. longer hue uses the larger distance. increasing hue always moves toward larger hue angles, while decreasing hue always moves toward smaller angles. The default is usually the shorter path.
Contrast and browser support
A darker OKLCH color is not automatically accessible. Check the final rendered foreground and background pair with a contrast checker. For normal text, WCAG commonly requires a ratio of at least 4.5:1. Large text commonly requires 3:1.
Provide a conventional fallback before newer syntax. Use @supports when a rule depends on color-mix().
.button {
background: #3b82f6;
background: oklch(62% 0.19 255);
}
@supports (color: color-mix(in oklch, red, blue)) {
.button:hover {
background: color-mix(in oklch, var(--brand), black 15%);
}
}Browsers that reject oklch() keep the first declaration. Unsupported color-mix() rules are skipped.
Exercise
How would you create a brand variant that is 20% lighter while keeping its chroma and hue?
Show answer
Use oklch(from var(--brand) calc(l + 0.2) c h), then check its contrast against the intended text color.