@pbroom/color-kitContrast

contrastRatio

Returns the WCAG 2.1 contrast ratio between two colors, from 1 (identical luminance) to 21 (black on white).

functionimport { contrastRatio } from '@pbroom/color-kit';metrics.ts:174
function contrastRatio(
  color1: Color,
  color2: Color,
  options?: ContrastOptions,
): number;

Symmetric in its arguments. Colors are measured as in relativeLuminance; the result is unrounded, so black on white is 20.999999999999986 rather than exactly 21.

Parameters

color1Color
First color (order does not matter).
color2Color
Second color.
options?ContrastOptions
Display gamut and channel precision.

Returns

numberContrast ratio in [1, 21].

Throws

  • When options.gamut is not 'srgb' or 'display-p3'.

Example

TypeScript
import { contrastRatio, parse } from '@pbroom/color-kit';

contrastRatio(parse('#777'), parse('#fff')); // → ≈ 4.478
contrastRatio(parse('#000'), parse('#fff')).toFixed(2); // → '21.00'

See also