Function Signature
js
ensureContrast(fg: string, bg: string, desired?: number, direction?: "auto" | "lighter" | "darker"): stringParameters
fg(string): Foreground HEX color string.bg(string): Background HEX color string.desired(number, optional): Target contrast ratio. Defaults to4.5(WCAG AA for normal text).direction("auto" | "lighter" | "darker", optional): How to adjust the foreground color. Defaults toauto.
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
contrastRatioto check compliance against the background. - Converts
fgto HSL viahexToRgbandrgbToHsl. - 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.