Contrast Auditor
Turn the WCAG contrast formula into a tool: compute the ratio of two hex colours and decide which accessibility levels the pair passes.
Statement
Story
The design system review is tomorrow and nobody has checked whether the palette is readable. Instead of pasting colours into a website one by one, you write an auditor that reads many colour pairs and reports the contrast ratio and the WCAG verdicts for each.
The formula
For a colour #RRGGBB (a three-digit #RGB colour means every digit is doubled, so #0af is #00aaff; hex letters may be upper or lower case):
- Take each channel
v(0 to 255) and computec = v / 255. - Linearise it:
lin = c / 12.92ifc <= 0.04045, otherwiselin = ((c + 0.055) / 1.055) ^ 2.4. - Relative luminance:
L = 0.2126 * R + 0.7152 * G + 0.0722 * Busing the three linearised channels. - Contrast ratio:
(L_lighter + 0.05) / (L_darker + 0.05). It is always between 1 and 21, and it does not matter which of the two colours is the text.
The verdicts
- AA: normal text needs a ratio of at least
4.5. - AA-large: large text needs a ratio of at least
3. - AAA: normal text needs a ratio of at least
7.
Decide every verdict from the exact, unrounded ratio. Only the printed ratio is rounded.
Input
The first line holds N (1 ≤ N ≤ 100). Each of the next N lines holds two colours, the foreground and the background, separated by a space.
Output
N lines: <ratio> <AA> <AA-large> <AAA>, with the ratio rounded to two decimals and each verdict printed as PASS or FAIL. The ratio is compared with a tolerance of 0.006.
Example
Input:
2
#000000 #ffffff
#777777 #ffffff
Output:
21.00 PASS PASS PASS
4.48 FAIL PASS FAIL
Black on white is the maximum, 21:1. Mid grey #777777 on white is just below the 4.5:1 line, so it fails AA for normal text but is fine for large text.
Sample input
2 #000000 #ffffff #777777 #ffffff
Hints
Stuck? Hints are optional, and each one lowers the points you earn for solving this challenge.
- Hint 1Costs 10 points
- Hint 2Costs 10 points
Reveal the previous hint first
- Hint 3Costs 15 points
Reveal the previous hint first
Lessons that teach this
Stuck on the ideas rather than the puzzle? These lessons cover what you need.