• You have an element with a configurable background color, and you’d like to calculate whether the foreground text should be light or dark. • Seems easy enough, especially knowing how mindful we ought to be with accessibility. • There have been a few drafts of a specification function for this functionality, most recently, contrast-color() (formerly color-contrast() ) in the CSS Color Module Level 5 draft. • But with Safari and Firefox being the only browsers that have implemented it so far, the final version of this functionality is likely still a ways off. • There has been a lot of functionality added to CSS in the meantime; enough that I wanted to see whether we could implement it in a cross-browser friendly way today. • Here’s what I have: color: oklch(from round(1.21 - L) 0 0); Let me explain how I got here.
Article Summaries:
- The article discusses how to approximate the draft CSS function contrast‑color()-currently only supported in Safari and Firefox-using existing CSS features. The author explains the WCAG 2.2 luminance‑based contrast formula, shows how it can be translated into a complex CSS calc expression that returns either black or white, and notes the difficulty of maintaining such code. They then propose a simpler approach that leverages perceptual lightness from the CIELAB color space, suggesting that a threshold on the L* value could decide between black or white text. The piece highlights the trade‑offs between accuracy, readability, and cross‑browser compatibility.
Sources: