CSS contrast-color() for Readable Text
Readable text without manual contrast checks
Picking readable text used to mean hardcoding color: white or color: black for each background. contrast-color() does the math for you. It returns black or white, whichever has more contrast against the given color.
The old hack vs the modern fix
View demo/* Hardcode a text color per background */
.badge-blue {
background: #1e40af;
color: white;
}
.badge-yellow {
background: #fde047;
color: black;
}
/* Repeat for every color variant */.badge {
background: var(--bg);
color: contrast-color(var(--bg));
}Contrast color browser support
Live demo
Why the modern way wins
Zero guesswork
The browser calculates contrast automatically. No WCAG math, no hardcoded overrides for each background.
Themeable by default
Change --bg to any color and the text color adjusts. Works with dynamic colors and user preferences.
Readable by default
contrast-color() picks the stronger of black or white. Mid-tone backgrounds can still fall below WCAG AA with both, so check those.
- Old Approach
- Manual
- Hardcoded per background
- Modern Approach
- contrast-color()
- Automatic black or white
- Lines Saved
- 10 → 4
- Per color variant
How it works
contrast-color(bg) takes a background color and returns black or white, whichever has more contrast against that background. It does not guarantee WCAG AA. Mid-tone backgrounds can fail with both, so check them. No JavaScript, no preprocessor, no lookup table.
The old approach meant manually choosing color: white or color: black for each background, and repeating that decision every time a new color was added. With user-generated colors or dynamic themes, this quickly becomes unmanageable in plain CSS.
Combine it with custom properties for maximum flexibility: color: contrast-color(var(--bg)) means you only define --bg and the browser handles the rest. It became Baseline Newly available in 2026 (Chrome 147, Firefox 146, Safari 26, Edge 147).