Sub topic 5
Modern color: oklch() and color-mix()
This chapter assumes you know hex, rgb(), and hsl() notation, and that you can define and read CSS custom properties. Here you will write colors with oklch() and derive new shades with color-mix().
Why hsl() falls short
In hsl(), equal lightness values do not look equally bright. hsl(60 100% 50%) (yellow) looks far brighter than hsl(240 100% 50%) (blue), even though both say 50%. If you build a palette by changing only the hue, some colors look washed out and others look heavy. Text contrast also becomes hard to predict.
oklch() is based on how people perceive color. Its lightness value tracks perceived brightness, so colors with the same lightness look about equally bright.
The oklch() syntax
.swatch {
background-color: oklch(55% 0.2 260);
}The three values are:
| Value | Meaning | Typical range |
|---|---|---|
| L (lightness) | Perceived brightness | `0%` (black) to `100%` (white) |
| C (chroma) | How vivid the color is | `0` (gray) to about `0.37` |
| H (hue) | Position on the color wheel, in degrees | `0` to `360` |
Alpha works as it does in rgb(): add a slash, as in oklch(55% 0.2 260 / 0.5).
To make a family of related colors, keep chroma and hue fixed and change only lightness. The steps will look evenly spaced.
Deriving shades with color-mix()
color-mix() blends two colors. You choose the color space where the blending happens, then list the colors with optional percentages.
:root {
--brand: oklch(55% 0.2 260);
--brand-light: color-mix(in oklch, var(--brand), white 30%);
}
.button {
background-color: var(--brand);
color: white;
}
.button:hover {
background-color: var(--brand-light);
}The result is 70% brand and 30% white. If you give only one percentage, the other color receives the remainder. If you give none, the mix is 50/50. Because the shade comes from --brand, changing the brand color updates the hover color automatically.
flowchart LRCommon errors
- Forgetting the color space.
color-mix(var(--a), var(--b))is invalid. Thein <space>part is required. - Mixing in the wrong space. Mixing in
srgboften gives duller midpoints than mixing inoklch. Pick the space deliberately. - Percentages that add up to more than 100%. The values are scaled down proportionally, and a total under 100% makes the result partly transparent. Keep totals at 100% unless you want that.
- Expecting every oklch() color to display. Some combinations of high chroma and certain lightness values fall outside what a screen can show. The browser maps them to the nearest displayable color, so two very different chroma values can end up looking the same.
Exercise
You have --brand: oklch(55% 0.2 260);. Write a declaration for --brand-dark that mixes the brand color with black, using 20% black, in the oklch space.
Show answer
--brand-dark: color-mix(in oklch, var(--brand), black 20%); The result is 80% brand and 20% black.