tsx
Pure CSS Auto-Contrast Text Color
You can automatically pick black or white color based on a background color using a only CSS.
The trick abuses relative color syntax in oklch. It extracts the perceptual lightness (l) of the background, subtracts it from a threshold (0.6), and multiplies by infinity. The result is either +infinity (clamped to white) or -infinity (clamped to black). Zero chroma and hue ensure a pure achromatic result.
Perfect for dynamic badges, tags, or any element where the background color is unpredictable. Works in all modern browsers today.
<Badge
style={{
backgroundColor: tag.color,
color: `oklch(from ${tag.color} calc((0.6 - l) * infinity) 0 0)`,
}}
>
{tag.name}
</Badge>
css
lubosmato