Sigra.A11y.Contrast (Sigra v1.20.0)

Copy Markdown View Source

WCAG 2.2 contrast ratio calculator for deterministic accessibility assertions.

Implements the W3C relative luminance formula and contrast-ratio formula exactly as specified in WCAG 2.2 Success Criterion 1.4.3 (Contrast — Minimum).

Usage

iex> Sigra.A11y.Contrast.ratio("#1d4ed8", "#ffffff")
5.17...  # >= 4.5 passes WCAG AA for normal text

References

Summary

Functions

Returns the WCAG contrast ratio between two hex colors.

Returns the WCAG relative luminance for a hex color string.

Functions

ratio(fg, bg)

@spec ratio(String.t(), String.t()) :: float() | {:error, String.t()}

Returns the WCAG contrast ratio between two hex colors.

The ratio is always >= 1.0. Direction (fg vs bg) does not matter — the function returns the same value regardless of argument order.

Returns {:error, reason} when either color is malformed.

Thresholds (WCAG 2.2)

StandardNormal textLarge text / bold
AA4.5:13.0:1
AAA7.0:14.5:1

Examples

iex> Sigra.A11y.Contrast.ratio("#000000", "#ffffff")
21.0

iex> Sigra.A11y.Contrast.ratio("#1d4ed8", "#ffffff")
5.17...

relative_luminance(hex)

@spec relative_luminance(String.t()) :: float() | {:error, String.t()}

Returns the WCAG relative luminance for a hex color string.

Accepts #rrggbb and #RRGGBB forms (6-digit hex with leading #).

Returns a float in [0.0, 1.0] on success, or {:error, reason} when the color string is malformed.

Examples

iex> Sigra.A11y.Contrast.relative_luminance("#000000")
0.0

iex> Sigra.A11y.Contrast.relative_luminance("#ffffff")
1.0