The WCAG Contrast Ratio, Explained (With a Live Checker)

javascript dev.to

Is your text readable on that background? There's a precise, math-backed answer — the WCAG contrast ratio — and you can compute it in ~10 lines. Here's a live checker, no library.

🌗 Try it (pick fg + bg colors): https://dev48v.infy.uk/solve/day18-contrast-checker.html

The math (it's exact)

  1. Hex → RGB (0–255 → 0–1).
  2. Linearize each channel (undo sRGB gamma): if c ≤ 0.03928, c/12.92, else ((c+0.055)/1.055)^2.4.
  3. Relative luminance = 0.2126·R + 0.7152·G + 0.0722·B (green is weighted heaviest — your eyes are most sensitive to it).
  4. Ratio = (L_lighter + 0.05) / (L_darker + 0.05) — ranges 1:1 (identical) to 21:1 (black on white).

The thresholds

  • AA normal text ≥ 4.5:1, large text ≥ 3:1
  • AAA normal ≥ 7:1, large ≥ 4.5:1
  • "Large" = ≥18pt (or 14pt bold)

Sanity check: #000 on #fff = 21:1 (max); #777 on #fff ≈ 4.48:1 (fails AA-normal, passes AA-large).

Why bother

~1 in 12 people have some color-vision deficiency; low contrast hurts everyone in sunlight. And never rely on color alone to convey meaning.

🔨 Full build (hex→rgb → linearize → luminance → ratio → thresholds) on the page: https://dev48v.infy.uk/solve/day18-contrast-checker.html

Part of SolveFromZero. 🌐 https://dev48v.infy.uk

Source: dev.to

arrow_back Back to Tutorials