Skip to content
colors

contrastRatio

The `contrastRatio` function calculates the WCAG contrast ratio between two colors, expressed as a number rounded to two decimals. The related `isAccessible` helper evaluates whether the contrast passes WCAG AA or AAA standards.

1 min read210 words

Function Signatures

js

contrastRatio(a: string, b: string): number
isAccessible(fg: string, bg: string, level?: "AA" | "AAA", size?: "normal" | "large"): boolean

Parameters

  • a (string): First HEX color string.
  • b (string): Second HEX color string.
  • fg (string): Foreground color in HEX (for isAccessible).
  • bg (string): Background color in HEX (for isAccessible).
  • 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 (true if the contrast meets WCAG criteria, otherwise false).

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 luminance function to calculate relative luminance for each color.
  • Formula: (L1 + 0.05) / (L2 + 0.05), where L1 ≥ 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).
  • isAccessible is a shortcut for checking compliance with WCAG accessibility standards.

Previous

luminance

Next

ensureContrast


Top-Werkzeuge

BoardlyLinksyChromoCodeHub

ReadyTools

KarriereKontaktWerkzeuge
Preise7 Tage gratis
AnleitungenDocsBlogUpdatesLaraVault

Sprache wählen

Thema wählen

© 2026 ReadyTools. Alle Rechte vorbehalten.