Skip to content
colors

ensureContrast

The `ensureContrast` function adjusts the lightness of a foreground color to ensure it meets a target WCAG contrast ratio against a background color. If the ratio is already sufficient, the original color is returned.

1 min read204 words

Function Signature

js

ensureContrast(fg: string, bg: string, desired?: number, direction?: "auto" | "lighter" | "darker"): string

Parameters

  • fg (string): Foreground HEX color string.
  • bg (string): Background HEX color string.
  • desired (number, optional): Target contrast ratio. Defaults to 4.5 (WCAG AA for normal text).
  • direction ("auto" | "lighter" | "darker", optional): How to adjust the foreground color. Defaults to auto.

Return Value

A HEX color string adjusted to meet or exceed the desired contrast ratio. If the input already meets the ratio, the original foreground color is returned.

js

ensureContrast("#ff6600", "#ffffff");
// "#b34700" (adjusted to meet ratio)

ensureContrast("#000000", "#ffffff");
// "#000000" (unchanged, already sufficient)

Examples

js

// Enforce AA standard (4.5)
console.log(ensureContrast("#888888", "#ffffff"));
// "#5c5c5c"

// Force lighter adjustment only
console.log(ensureContrast("#333333", "#000000", 7, "lighter"));
// "#b3b3b3"

// Force darker adjustment only
console.log(ensureContrast("#cccccc", "#ffffff", 7, "darker"));
// "#4d4d4d"

Implementation Details

  • Uses contrastRatio to check compliance against the background.
  • Converts fg to HSL via hexToRgb and rgbToHsl.
  • Adjusts lightness (l) using a binary search method until the ratio is met.
  • Supports lighter, darker, or automatic mode where both directions are tried and the minimal adjustment is chosen.
  • Final result is converted back into HEX with rgbToHex.

Usage Notes

  • WCAG contrast thresholds: AA = 4.5 (normal) / 3.0 (large), AAA = 7.0 (normal) / 4.5 (large).
  • Best used for dynamically generating accessible text or UI colors.
  • Automatic mode ensures minimal perceptual change while meeting requirements.

Previous

contrastRatio

Next

getContrastColor


Herramientas destacadas

BoardlyLinksyChromoHub de Código

ReadyTools

CarrerasContactoHerramientas
Precios7 días gratis
GuíasDocsBlogUpdatesLaraVault

Seleccionar idioma

Establecer tema

© 2026 ReadyTools. Todos los derechos reservados.