Function Signatures
js
contrastRatio(a: string, b: string): number
isAccessible(fg: string, bg: string, level?: "AA" | "AAA", size?: "normal" | "large"): booleanParameters
a(string): First HEX color string.b(string): Second HEX color string.fg(string): Foreground color in HEX (forisAccessible).bg(string): Background color in HEX (forisAccessible).level("AA" | "AAA", optional): WCAG compliance level. Defaults to"AA".size("normal" | "large", optional): Text size category. Defaults to"normal".
Return Values
contrastRatio→ A number representing the ratio, e.g.4.53.isAccessible→ Boolean (trueif the contrast meets WCAG criteria, otherwisefalse).
Examples
js
contrastRatio("#000000", "#ffffff");
// 21 (maximum contrast)
contrastRatio("#ff6600", "#ffffff");
// ~3.99
isAccessible("#ff6600", "#ffffff", "AA", "normal");
// false (needs 4.5+)
isAccessible("#ff6600", "#ffffff", "AA", "large");
// true (requires 3+)
isAccessible("#000000", "#ffffff", "AAA");
// true (meets 7+ requirement)WCAG Compliance Levels
- AA (Normal text): Requires ratio ≥ 4.5.
- AA (Large text): Requires ratio ≥ 3.
- AAA (Normal text): Requires ratio ≥ 7.
- AAA (Large text): Requires ratio ≥ 4.5.
Implementation Details
- Internally uses the
luminancefunction to calculate relative luminance for each color. - Formula:
(L1 + 0.05) / (L2 + 0.05), whereL1 ≥ L2. - Ratio values are rounded to 2 decimal places for readability.
Usage Notes
- A ratio of 1 means no contrast (same color).
- A ratio of 21 represents maximum contrast (black vs white).
isAccessibleis a shortcut for checking compliance with WCAG accessibility standards.