Highest contrast colour in pure CSS

I’m setting up a button component with a few different variants (.btn-primary, .btn-success, .btn-danger, that sort of thing)—these switch the background colour. Is there a way to set this up so the foreground colour is automatically selected between a dark and light option for whichever gives the most contrast? In pure CSS that is, rather than using some JavaScript. Being able to do an if-then-else for whether the L component of var(—btn-bg) is <50 would do the trick to select between the two as an approximation, but I’m not sure how to go from there. Is this possible?
5 Replies
prophile
prophileOP4mo ago
I’ve just learned about a contrast-color() function, but unfortunately not supported anywhere yet
Kevin Powell
Kevin Powell4mo ago
It probably won't get support anytime soon either, I think because they want to make sure they use the right algorithm One of the reasons is because you can't simply use the l value and flip it when it's at 50%. 50% lightness yellow is very different from 50% lightness blue, for example. They're are more modern algorithms that are better, and I have no idea how they work 😄 There are js libraries that can do this for you that are light weight
prophile
prophileOP4mo ago
Even in oklab? I thought the idea of CIELAB was that it was perceptual. Alas Thanks for answering 🙂 I’ll go with just specifying manually in each case instead I think Also now realising I’d specified “L” without a colourspace, forgive my needless ambiguity
Kevin Powell
Kevin Powell4mo ago
ha, np, I just assumed it was hsl, that's usually where people start. I believe even in lab, things can get a bit wonky though. This is the tool that I was thinking of: https://colorjs.io/ I think you can configure it to use different forms of color interpolation as well
prophile
prophileOP4mo ago
Swish, thanks
Want results from more Discord servers?
Add your server