Skip to the content ForoHackers
Log inJoin

Computing the WCAG contrast ratio by hand (and why #767676 is famous)

AccessibilityCSSUser experience
#1097 · tabs_over_spaces_42 · · Report

"Is this grey text readable?" has a measurable answer: the contrast ratio. The formula is short enough to implement in a few lines, which is better than trusting a checker you do not understand.

def lin(c):
    c /= 255
    return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4

def luminance(r, g, b):
    return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)

def contrast(fg, bg):
    hi, lo = sorted((luminance(*fg), luminance(*bg)), reverse=True)
    return (hi + 0.05) / (lo + 0.05)

print(round(contrast((0x76, 0x76, 0x76), (255, 255, 255)), 2))   # 4.54

What it does: converts each sRGB channel to linear light (undoing the gamma curve), weights green most because the eye is most sensitive to it, then takes the ratio of the lighter to the darker, with 0.05 added to avoid dividing by zero for black.

Thresholds in the guidelines: 4.5:1 for normal text, 3:1 for large text and for the boundaries of controls, 7:1 for the stricter level. #767676 on white is the lightest grey that still passes 4.5:1, which is why it appears in a lot of design discussions.

Two caveats: the ratio says nothing about font weight, size or the quality of the typeface, and a pass does not mean readable for everyone (it says nothing about glare, or small text on a busy background). It is a floor, not a goal.

#1744 · ElTioDeLosLeds · · Report

Lo usé al elegir colores de LED para un panel frontal, y mi "azul sobre negro" favorito suspende por mucho. El azul tiene el peso más pequeño (0,0722), así que un azul puro es muy oscuro en luminancia. Coincide con lo que se siente al entrecerrar los ojos para leerlo.

#1745 · dual_boot_dani · · Report

Útil. Para los que trabajamos con tema claro y oscuro: hay que comprobar el ratio en los dos temas. El gris que pasa sobre blanco puede fallar sobre un fondo oscuro, y el diseño que solo se mira en un tema tiene la mitad de las pruebas hechas.

#1746 · polyglot_parser · · Report

Small linguistic note from someone who stares at text: contrast is only one axis of legibility. Line length, line spacing, and the shapes of the letters matter just as much for people who read slowly or with a screen magnifier. A grey that passes at 16 px with generous spacing can be tiring at 12 px packed tight.

#1747 · tabs_over_spaces_42 · · Report

Fair point on spacing and size. I will add a line to our review checklist: contrast ratio, then size and line spacing, then keyboard focus. In that order, and not only the first.

Log in or join to reply.