Menu

Checking a whole palette for WCAG contrast in 20 lines of JavaScript
📰

Checking a whole palette for WCAG contrast in 20 lines of JavaScript

DEV Community: css·Casper Tran·2 days ago
#Dv2Guik6
#devtocss#devto#dev#background#muted
Reading 0:00
15s threshold

Most of us check contrast one pair at a time: open the DevTools color picker on a paragraph, glance at the ratio, move on. That catches body text. It misses the pairs nobody inspects: the label on the primary button, the muted caption sitting on a card instead of the page, the outline of an input.

Here is the formula, a short script that checks every pair a palette actually uses, and what it found on two demo palettes I had lying around.

The formula

WCAG 2.2 defines contrast from relative luminance. Linearize each sRGB channel, weight them, then compare the lighter and darker color:

const lin = ( c ) => { c /= 255 ; return c <= 0.04045 ? c / 12.92 : ( ( c + 0.055 ) / 1.055 ) ** 2.4 ; } ; const lum = ( [ r , g , b ] ) => 0.2126 * lin ( r ) + 0.7152 * lin ( g ) + 0.0722 * lin ( b ) ; const hex = ( h ) => [ 1 , 3 , 5 ] . map ( ( i ) => parseInt ( h . slice ( i , i + 2 ) , 16 ) ) ; const ratio = ( a , b ) => { const [ x , y ] = [ lum ( hex ( a ) ) , lum ( hex ( b ) ) ] ; return ( Math .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.