Colore JS

Search documentation

Find a function or jump to a section.
v2.0.1

ensureContrast

ensureContrast turns #777777 on white into #767676. It finds a passing foreground by moving lightness as little as it can under the rules you choose. You get the color and a flag saying whether the search succeeded.

Example

import { ensureContrast } from 'colore-js';
import { ensureContrast as fixContrast } from 'colore-js/fn';

ensureContrast('#777777', '#ffffff').color.hex(); // '#767676'
fixContrast('#777777', '#ffffff');
// { color: '#767676', satisfied: true, iterations: 1 }
before, 4.48:1 contrast, #777777 on #ffffff
after, 4.54:1 contrast, #767676 on #ffffff

Syntax

// colore-js
ensureContrast(foreground: ColorInput | Color, background: ColorInput | Color, options?: EnsureContrastOptions): ResolveResult

// colore-js/fn
ensureContrast(foreground: ColorInput, background: ColorInput, options?: EnsureContrastOptions):
  { color: string; satisfied: boolean; unsatisfied?: string[]; iterations: number }

Parameters

NameTypeDescription
foreground, backgroundColorInput | ColorThe color to adjust and the background to check it against.
options.algorithm / options.intentContrastAlgorithm / ContrastIntentDefaults to WCAG 2 and normal text. Choose 'largeText', 'ui', 'focus' or 'decorative' for another context.
options.level / options.target'aa' | 'aaa' / numberDefault WCAG AA body text target is 4.5. Set a level or give an explicit ratio or absolute APCA Lc.
options.preserve'auto' | 'hue' | 'chroma' | 'both'The default tries to keep hue first, then chroma. Choose an explicit rule to require it.
options.direction'auto' | 'darken' | 'lighten'The direction lightness may move. With automatic direction and preservation, the search can also try a gray.

Returns

The result contains color, satisfied and iterations. When the search cannot meet the target, color is the original foreground and unsatisfied is ['contrast']. The root export returns a Color in color. The /fn export returns a CSS string, which can be Display P3 or OKLCH for a wide-gamut color.

Throws

A ColorError for invalid colors, unsupported options or a target outside the measure’s accepted range.

Repair a pair for WCAG AAA

import { ensureContrast as fixContrast } from 'colore-js/fn';

fixContrast('#3b82f6', '#fff', { level: 'aaa' });
// { color: '#0452c2', satisfied: true, iterations: 1 }

fixContrast('color(display-p3 1 0 0)', '#fff', { direction: 'lighten', target: 7 });
// { color: 'color(display-p3 1.00000 0.00000 0.00000)', satisfied: false, unsatisfied: ['contrast'], iterations: 1 }

Check satisfied before applying the result when you set a strict preservation rule or direction. Use rendered sRGB colors for WCAG 2 checks.