Skip to content
← Tips

Pick black or white text from a colour in pure CSS

Relative colour syntax plus clamp() gives a contrast switch with no JavaScript.

  • css
  • color
  • oklch

The palette swatches on this site choose their label colour like this:

.swatch {
	background: var(--c);
	color: oklch(from var(--c) clamp(0, (0.62 - l) * 1000, 1) 0 0);
}

oklch(from …) exposes the background’s lightness as l (0–1). (0.62 - l) * 1000 is a huge positive number for dark colours and a huge negative one for light colours; clamp(0, …, 1) snaps it to exactly 1 (white text) or 0 (black text). Chroma and hue are zeroed, so the result is always a neutral.

0.62 is the switch point; nudge it to taste. Works in every current evergreen browser.

esc