Sub topic 5
Measuring contrast with WCAG ratios
Why "high contrast" needs a number
The previous chapter treated contrast as a cue: elements that differ from their surroundings in value, color, or weight get noticed. That works for hierarchy, but it leaves a gap. Whether gray text on white "looks fine" depends on your monitor, your eyesight, the room's lighting, and how long you have stared at the design. The Web Content Accessibility Guidelines (WCAG) close the gap with a formula that turns any two colors into a single number. This chapter assumes you know hex and rgb() color notation and basic CSS custom properties. It covers how the number is computed, which thresholds apply to which elements, and where the number misleads you.
The contrast ratio formula
A WCAG contrast ratio compares the relative luminance of two colors. Relative luminance is a value from 0 (black) to 1 (white) that approximates how bright a color appears to the human eye. The ratio is:
(L_lighter + 0.05) / (L_darker + 0.05)The result runs from 1:1 (identical colors) to 21:1 (black on white). The order of foreground and background does not matter, because the formula always puts the lighter luminance on top.
The 0.05 offset models ambient light that reflects off a screen. It also prevents division by zero for pure black.
Computing relative luminance
Luminance takes three steps:
- Divide each 8-bit channel (red, green, blue) by 255 to get a value from 0 to 1.
- Undo the sRGB gamma curve, so the value is proportional to physical light. Small values use a linear segment, and larger values use a power of 2.4.
- Weight the three linear channels by how sensitive the eye is to each: 0.2126 for red, 0.7152 for green, and 0.0722 for blue.
The weights explain why pure green looks bright and pure blue looks dark, even though both are "255" in one channel. They also explain why you cannot judge contrast by averaging channel values.
A contrast checker you can run
The function below implements the formula. It is the version from the topic plan, extended with a hex parser and a grader so you can test real design tokens. Save it as contrast.js and run it with node contrast.js.
function channel(value) {
const s = value / 255;
return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
}
function luminance([r, g, b]) {
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}
function contrastRatio(colorA, colorB) {
const a = luminance(colorA);
const b = luminance(colorB);
const lighter = Math.max(a, b);
const darker = Math.min(a, b);
return (lighter + 0.05) / (darker + 0.05);
}
function hexToRgb(hex) {
const h = hex.replace("#", "");
const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
const n = parseInt(full, 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function grade(ratio) {
// Compare the unrounded ratio. 4.499 must not pass as 4.5.
return {
ratio: ratio.toFixed(2),
normalTextAA: ratio >= 4.5,
largeTextAA: ratio >= 3,
normalTextAAA: ratio >= 7,
uiComponentAA: ratio >= 3,
};
}
const pairs = [
["#000000", "#ffffff"],
["#767676", "#ffffff"],
["#777777", "#ffffff"],
["#0b57d0", "#ffffff"],
];
for (const [fg, bg] of pairs) {
console.log(fg, "on", bg, grade(contrastRatio(hexToRgb(fg), hexToRgb(bg))));
}The first pair prints 21.00. The second prints 4.54 and passes AA for normal text. The third, #777777, prints 4.48 and fails, even though it is visually almost identical to #767676. The primary button color #0b57d0 from the earlier button example gives roughly 6.4:1 on white, so white text on a filled primary button passes comfortably.
Which threshold applies to what
WCAG defines two conformance levels for text contrast, AA and AAA, and a separate rule for non-text elements. Most teams and most legal standards target AA.
| Element | AA minimum | AAA minimum |
|---|---|---|
| Normal text | 4.5:1 | 7:1 |
| Large text | 3:1 | 4.5:1 |
| UI component boundaries and states, meaningful graphics | 3:1 | no separate level |
"Large text" has a precise meaning. It is at least 18 pt (24 CSS px) at regular weight, or at least 14 pt (about 18.66 CSS px) at bold weight. A heading at 1.563rem (25 px) from the type scale qualifies as large. Body text at 1rem does not, no matter how bold you make it.
The UI component rule (WCAG 2.1 success criterion 1.4.11, Non-text Contrast) covers visual information needed to identify a control and its state. That includes the border of a text input, the focus indicator, the checked state of a checkbox, and the strokes of an icon that carries meaning on its own. It compares the element against the colors adjacent to it. A button with a filled background needs 3:1 between the fill and the page, but only if the fill is the sole thing that marks it as a button. If the button text already makes its purpose clear, the fill may be lower contrast.
Some things are exempt:
- Disabled controls.
- Pure decoration.
- Logos and brand names.
- Text that is incidental, such as text inside a photo.
Do not stretch these exemptions. A "disabled-looking" link that is actually active is not exempt.
Applying the thresholds to the earlier button example
In the primary and secondary buttons from the previous chapter, both use #0b57d0. The primary button has white text on a blue fill, about 6.4:1. The secondary button has blue text on a transparent background, which is the same ratio against a white page. Both pass 4.5:1 for their labels. The secondary button's 2 px border also passes the 3:1 rule for component boundaries. Hierarchy comes from fill and weight, and accessibility comes from every part clearing its threshold.
Encoding ratios in your design tokens
The most reliable way to keep ratios from drifting is to test them once when you define your colors, and then use only the tested pairs. Custom properties make this practical.
:root {
/* Text on --surface: tested pairs only */
--surface: #ffffff;
--text: #1b1b1f; /* about 17:1 on --surface */
--text-muted: #5f6368; /* about 6:1 on --surface, passes AA */
--accent: #0b57d0; /* about 6.4:1 on --surface */
/* Component boundaries need 3:1 against --surface */
--border-control: #767676; /* about 4.5:1, passes with margin */
}
body {
background: var(--surface);
color: var(--text);
}
.meta {
color: var(--text-muted);
}
input {
border: 1px solid var(--border-control);
}
:focus-visible {
outline: 3px solid var(--accent);
outline-offset: 2px;
}A common mistake is a light gray input border such as #cccccc. It looks tidy but measures about 1.6:1 on white, which fails the 3:1 rule. Users with low vision may not see where the field is.
Edge cases where the number misleads
Transparency
A color with an alpha channel has no single luminance. Its visible color depends on what lies behind it. Composite the color over its actual background first, then compute the ratio on the result. For each channel, the blended value is alpha * foreground + (1 - alpha) * background. The same applies to opacity on an element: setting opacity: 0.6 on a text element lowers its effective contrast, and the original ratio no longer holds.
Gradients and images
When text sits on a gradient or photo, the background is many colors at once. Check the worst case: the spot where the text sits on the color closest in luminance to the text. For photos, a common fix is a semi-opaque scrim (a dark overlay) behind the text. You then test the text against the scrim blended with the lightest part of the photo.
State changes
Hover, focus, active, visited, and dark-mode variants each need their own check. Teams often test the default state and forget that a hover color lightens the text below 4.5:1. Dark mode is not an inversion of the light palette. Pure white on pure black can be harsh, and a softer pair such as off-white on dark gray usually still clears 7:1.
Rounding
The WCAG threshold is exact. A computed ratio of 4.49 does not meet 4.5:1, and rounding it up to 4.5 is incorrect. This is why the grade function compares the unrounded number and only formats it for display.
Limits of the formula
The WCAG 2 formula ignores font weight (beyond the bold-large rule), font size within a category, and polarity. Light text on a dark background can look less readable than the same ratio would suggest on the reverse. A newer model called APCA is being researched for a future WCAG version, but WCAG 2.x ratios remain the standard that audits and regulations reference today. Use the ratio as a minimum, then judge the result visually.
Tools and where to check
You rarely compute ratios by hand. These tools use the same formula you just implemented:
- Browser DevTools. The color picker in Chrome and Firefox shows the ratio and marks the AA and AAA boundaries for the selected text.
- Dedicated contrast checkers, where you enter two hex values and read the result.
- Automated audits such as Lighthouse or axe, which flag text below its threshold. These cannot test text over images or gradients reliably, so check those by hand.
Summary
- The contrast ratio is
(L_lighter + 0.05) / (L_darker + 0.05), from 1:1 to 21:1. - AA requires 4.5:1 for normal text, 3:1 for large text, and 3:1 for meaningful UI components and graphics.
- Compare the unrounded value, composite transparent colors first, and test every state and the worst-case area of gradients and images.
- Treat a passing ratio as a floor. It does not guarantee readability, and it does not replace looking at the page.
Exercise
A paragraph uses #777777 text on a white background at 1rem regular weight. The ratio is 4.48:1. Does it meet WCAG AA? Name two different changes that would make it pass, and say whether the same color would pass if the text were a 2rem (32 px) regular-weight heading.
Show answer
It fails AA for normal text, because 4.48 is below 4.5 and you must not round up. Two fixes: darken the text to #767676 or darker (4.54:1 or higher), or change the background to something lighter than white, which is impossible, so darkening the text is the practical route. Raising the size to a large-text category would also work, since large text only needs 3:1. A 2rem (32 px) heading is large text, so #777777 on white passes AA there at 4.48:1.
Exercise
A text input has a 1 px border of #cccccc on a white page. Which WCAG requirement does this likely break, what ratio is required, and how would you fix it using the tokens in this chapter?
Show answer
It likely breaks the non-text contrast requirement (success criterion 1.4.11), which asks for at least 3:1 between a component's boundary and the adjacent color. #cccccc on white is about 1.6:1. Replace the border color with var(--border-control) (#767676, about 4.5:1), or any gray that measures at least 3:1 against the surface.