How I Built a WCAG Contrast Checker in 50 Lines of JavaScript.

Published: (February 18, 2026 at 06:38 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

I used to pick colors for a website by zooming in, squinting, and asking myself, “Is this readable? Yeah, probably.” Then I’d ship it. A few months ago a user with low vision emailed me because he couldn’t read light‑gray text on one of my sites. He wasn’t angry—just disappointed. That email stayed in my inbox, and when I built FontPreview I decided I wasn’t going to guess anymore. I added a contrast checker directly into the tool, and it only took about 50 lines of JavaScript.

The Math (It’s Not as Scary as It Looks)

The contrast ratio is calculated as:

(L1 + 0.05) / (L2 + 0.05)

where L1 is the relative luminance of the lighter color and L2 is that of the darker color. Here’s the luminance function in JavaScript:

function luminance(r, g, b) {
  const a = [r, g, b].map(v => {
    v /= 255;
    return v = 18.66 || (size >= 14 && isBold);

  if (ratio >= 7)   return { level: 'AAA',       class: 'aaa' };
  if (ratio >= 4.5) return { level: 'AA',        class: 'pass' };
  if (ratio >= 3 && isLarge) return { level: 'AA Large', class: 'aa-large' };
  return { level: 'FAIL', class: 'fail' };
}

The Part That Surprised Me

The hard part was realizing how many of my old designs would have failed these checks. That light‑gray text I thought looked “clean” and “minimal”? FAIL. That low‑contrast button I was proud of? FAIL.

You Can Try It Yourself

Try it at FontPreview. Pick any two colors, type some text, and the badge updates instantly—no math required.

One More Thing

The important part is that I stopped guessing. If you’re still checking colors by squinting at your screen, remember that someone out there—maybe the person who emailed me—is trying to read your work and can’t. Give the contrast checker a spin and make your designs more accessible.

0 views
Back to Blog

Related posts

Read more »