Approximating contrast-color() With Other CSS Features | CSS-Tricks
Briefly

Approximating contrast-color() With Other CSS Features | CSS-Tricks
"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 <your color> round(1.21 - L) 0 0);"
"WCAG provides the formulas it uses for calculating the contrast between two RGB colors and Stacie Arellano has described in great detail. It's based on older methods, calculating the luminance of colors (how perceptually bright they appear) and even tries to clamp for the limitations of monitors and screen flare: L1 + 0.05 / L2 + 0.05 ...where the lighter color ( L1) is on the top. Luminance ranges from 0 to 1, and this fraction is responsible for contrast ratios going from 1 (1.05/1.05) to 21 (1.05/.05)."
"The formulas for calculating the luminance of RGB colors are even messier, but I'm only trying to determine whether white or black will have higher contrast with a given color, and can get away with simplifying a little bit. We end up with something like this: L = 0.1910(R/255+0.055)^2.4 + 0.6426(G/255+0.055)^2.4 + 0.0649(B/255+0.055)^2.4 Which we can convert into CSS like this: calc(.1910*pow(r/255 + .055,2.4)+.6426*pow(g/255 + .055,2.4)+.0649*pow(b/255 + .055,2.4)) We can make this whole thing round to 1 or 0 using , 1 for white and 0 for black: round(.67913 - .1910*pow(r/255 + .055, 2.4) - .6426*pow(g/255 + .055, 2.4) - .0649*pow(b/255 +"
Choosing a readable foreground color requires computing which of white or black yields higher contrast against a configurable background. WCAG contrast uses luminance-based ratios computed from RGB values, producing contrast ratios from 1 to 21. The luminance computation can be approximated with weighted gamma-corrected RGB components. That approximation can be expressed in CSS using calc() and pow(), then rounded to produce a binary output (1 for white, 0 for black). A practical cross-browser approach maps the luminance into OKLCH and selects foreground via a rounded transform of the L channel.
Read at CSS-Tricks
Unable to calculate read time
[
|
]