Sub topic 10
Checking contrast on generated colors
Generated colors can look correct and still be unreadable. This chapter shows how to measure text contrast on colors produced by oklch(), color-mix() and relative color syntax, and how to build checks into your workflow.
It assumes you have read the earlier chapters on oklch() syntax, color-mix(), relative color syntax and custom-property tokens. You also need basic JavaScript to run the checking script.
Why lightness alone is not a contrast guarantee
In OKLCH, the L component is perceived lightness. Two colors with the same L look about equally light to a person, and two colors that differ by 0.4 in L look clearly different in lightness. That makes L a good guide for choosing colors.
It is not a contrast measurement. Three things get in the way:
- Chroma and hue move the result. At the same
L, a saturated yellow and a saturated blue produce different WCAG ratios against white. The ratio depends on relative luminance, which weights red, green and blue differently from OKLCH lightness. - Mixing changes the result in non-obvious ways. A
color-mix()blend of two accessible colors is not guaranteed to be accessible against a third. - Alpha depends on what is behind it. A translucent color has no contrast ratio of its own. You can only measure it after it is composited over its backdrop.
Treat L as a way to get close, and use a calculation to confirm.
What the standard measures
WCAG 2.x defines contrast as a ratio between the relative luminance of two colors, where luminance runs from 0 (black) to 1 (white):
ratio = (L_lighter + 0.05) / (L_darker + 0.05)The ratio runs from 1:1 (identical colors) to 21:1 (black on white). The usual thresholds at level AA are:
| Content | Minimum ratio |
|---|---|
| Body text (under about 24px, or under 19px bold) | 4.5:1 |
| Large text (about 24px or 19px bold and up) | 3:1 |
| UI components and focus indicators against their surroundings | 3:1 |
| Level AAA body text | 7:1 |
Relative luminance is computed from linear sRGB. Because it is defined on sRGB, it works from the color's sRGB rendering, even if your CSS uses oklch().
A newer model, APCA, predicts perceived contrast differently and depends on font size and weight. It is a candidate for future WCAG versions, but WCAG 2.x ratios are still what most audits and legal requirements use. This chapter uses WCAG 2.x.
A quick relationship between L and contrast
For a neutral grey (chroma 0), the luminance is the cube of OKLCH lightness: Y = L³. That gives a usable rule of thumb:
- White text needs a grey background of about
L ≤ 0.57to reach 4.5:1. - Black text needs a grey background of about
L ≥ 0.57. - Around
L = 0.57neither choice does much better than 4.5:1, so mid-tones are a poor home for text.
For example, oklch(0.5 0 0) has Y = 0.125. Against white that gives 1.05 / 0.175 = 6.0.
Chromatic colors drift away from this rule. That is the reason to compute the ratio rather than rely on a lightness cutoff.
Computing contrast for an oklch() color
This script converts OKLCH to linear sRGB, computes WCAG relative luminance, and prints pass or fail for a few text and background pairs. Save it as contrast.mjs and run node contrast.mjs with Node 18 or newer.
// contrast.mjs
// Lightness is 0-1 (so 62% is 0.62), hue is in degrees.
function oklchToLinearSrgb([L, C, hDeg]) {
const h = (hDeg * Math.PI) / 180;
const a = C * Math.cos(h);
const b = C * Math.sin(h);
const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
return [
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
];
}
const clamp01 = (x) => Math.min(1, Math.max(0, x));
function luminance(color) {
// Clamping each channel is a simple gamut clip.
const [r, g, bl] = oklchToLinearSrgb(color).map(clamp01);
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
}
function contrast(foreground, background) {
const a = luminance(foreground);
const b = luminance(background);
const [hi, lo] = a > b ? [a, b] : [b, a];
return (hi + 0.05) / (lo + 0.05);
}
const white = [1, 0, 0];
const black = [0, 0, 0];
const pairs = [
["white on grey 0.5", white, [0.5, 0, 0]],
["white on brand", white, [0.62, 0.19, 255]],
["black on brand", black, [0.62, 0.19, 255]],
["white on button", white, [0.6, 0.15, 250]],
["white on button hover", white, [0.52, 0.15, 250]],
];
for (const [name, fg, bg] of pairs) {
const ratio = contrast(fg, bg);
const verdict = ratio >= 4.5 ? "PASS" : "FAIL";
console.log(`${name.padEnd(24)} ${ratio.toFixed(2)} ${verdict}`);
}The first line prints 6.00 and PASS, matching the hand calculation above. Run the rest yourself. Note which of the brand pairs passes, because the answer for white text and black text on the same background is often not what the lightness number suggests.
The clamp matters. If a color is outside sRGB, the script clips it, while a browser applies its own gamut mapping, so the two can differ slightly. For colors comfortably inside sRGB the difference is negligible. For colors near the gamut edge, confirm with a browser-based checker.
Where to put the check
The check belongs wherever colors are decided, not at the end. The workflow below fits most token-based setups.
Useful places to run the check:
- A build or test step. Parse your token file, compute the ratios for the pairs you define, and fail the build when one drops below its threshold.
- Browser developer tools. Chromium and Firefox show a contrast ratio in the color picker for the selected element, computed from the final rendered colors.
- Visual review of states. Check hover, focus, active, disabled and dark mode, not only the default state.
Contrast across derived states
Each derivation can raise or lower contrast, so think about the direction before you pick a delta.
:root {
--button-bg: oklch(52% 0.15 250);
--button-text: white;
}
.button {
background: var(--button-bg);
color: var(--button-text);
}
/* Darker background: contrast with white text goes up. */
.button:hover {
background: oklch(from var(--button-bg) calc(l - 0.06) c h);
}
/* Lighter background: contrast with white text goes down. */
.button:disabled {
background: oklch(from var(--button-bg) calc(l + 0.25) calc(c * 0.4) h);
}The hover state moves in the safe direction, because white text gets more contrast on a darker background. Disabled controls are normally exempt from WCAG contrast requirements, but keep them readable enough that users can tell what the control says.
The same reasoning applies to tints:
.card {
--tint: color-mix(in oklch, var(--brand) 15%, white);
background: var(--tint);
color: oklch(25% 0.05 255);
}A 15% tint is very light, so dark text on it passes easily. A 60% tint is much closer to the brand color, and dark text on it may fall into the mid-tone zone where neither dark nor white text works well. Verify the tint steps you actually use.
Choosing text color automatically
Relative color syntax can pick black or white text from the background's lightness:
.badge {
--badge-bg: oklch(70% 0.14 150);
background: var(--badge-bg);
color: oklch(from var(--badge-bg) clamp(0, (l - 0.57) * -1000, 1) 0 0);
}When l is above 0.57 the expression is negative and clamps to 0 (black). When l is below 0.57 it clamps to 1 (white). This is a heuristic based on the grey analysis earlier. Because chroma and hue move luminance, it can choose the worse of the two colors for some backgrounds, and near the threshold both choices score only about 4.5:1. Use it for convenience, then verify the results with your script on the real token values.
CSS also defines a contrast-color() function that returns black or white for a given background. Browser support is still limited and the first version uses the WCAG 2 ratio, so check current support tables before depending on it, and keep a fallback color.
Transparency and layering
A color with alpha, for example oklch(62% 0.19 255 / 0.5), has no contrast ratio on its own. The measured color is the result of blending it with whatever is behind it. The same translucent button can pass on a white page and fail on a dark one.
Practical rules:
- Measure translucent text and backgrounds after compositing over the actual backdrop.
- Avoid putting text on a translucent color over an image or gradient, where the backdrop changes from point to point. Add a solid or high-opacity scrim behind the text instead.
- When you can, choose an opaque color.
color-mix()with a transparent or white second color gives a tint that is easy to measure, and it behaves the same on every page.
Non-text contrast
WCAG also sets a 3:1 minimum for UI components needed to identify controls, and for focus indicators. Generated colors affect these as well:
- A border built with
oklch(from var(--brand) l c h / 0.4)can drop below 3:1 against the page. If the border is the only thing that marks a text field, it needs to pass. - A focus ring should contrast with both the element and the page around it. A two-tone ring (an inner light line and an outer dark line) works on any background.
- Chart series, status icons and similar graphics need 3:1 against adjacent colors, and should not rely on color alone to carry meaning.
Common mistakes
- Equating a 4.5:1 ratio with comfortable reading. It is the minimum. Small or thin text, long passages and users with low vision benefit from more.
- Checking only light mode. If a dark theme reuses the same lightness deltas, hover may move in the unsafe direction there, because lightening a background reduces contrast with light text.
- Checking tokens but not their combinations. Contrast is a property of a pair. Keep a list of the pairs used in real components.
- Trusting the hue. If you rotate the hue to produce a family of status colors (success, warning, danger) at the same
LandC, their contrast ratios differ. Yellow and green at the same lightness give the text more luminance than blue does. - Ignoring gamut mapping. A high-chroma color that falls outside sRGB is mapped to something less saturated, with a different luminance than your hand calculation if it was computed without mapping.
Summary
OKLCH lightness gives you a good first guess at contrast, and the WCAG ratio gives you the answer. Generate colors with tokens, color-mix() and relative color syntax, then compute the ratio for each text and background pair, and re-check whenever you change a delta, a hue or a theme. Be especially careful with translucent colors, mid-tone backgrounds and states that lighten a background under light text.
Exercise
A button uses white text on oklch(0.5 0 0), which has a contrast ratio of 6.0:1. A designer changes the hover state to oklch(from var(--bg) calc(l + 0.1) c h). Without running code, does the hover state still meet 4.5:1 for normal text? Use Y = L³ for neutral greys.
Show answer
The hover background is oklch(0.6 0 0), so Y = 0.6³ = 0.216. The ratio against white is 1.05 / (0.216 + 0.05) = 1.05 / 0.266, which is about 3.95:1. That is below 4.5:1, so the hover state fails for normal text. Lightening the background lowered contrast with white text, so the hover should move darker instead.
Exercise
Why is color: oklch(from var(--bg) clamp(0, (l - 0.7) * -1000, 1) 0 0) a risky way to choose black or white text, and what would you do before shipping it?
Show answer
A cutoff of 0.7 sends backgrounds with lightness between about 0.57 and 0.7 to white text, where the contrast is often below 4.5:1, since the crossover point for neutral greys is near 0.57. Chroma and hue also change luminance, so no single lightness cutoff works for every color. Move the threshold toward 0.57 if you use this approach, compute the WCAG ratio for each real background and text pair with a script or the browser's developer tools, and fail the build for pairs under 4.5:1.