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 }
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
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.
Related
- Check color contrast in JavaScript to measure and repair a pair
- isReadable to check a target without adjusting the color
- audit to find failing pairs in a palette