This is a great post by Lea Verou all about conditional statements in CSS:
A couple days ago, I posted about the recent CSS WG resolution to add an if() function to CSS. Great as it may be, this is still a long way off, two years if everything goes super smoothly, more if not. So what can you do when you need conditionals right now?
You may be pleased to find that you’re not completely out of luck. There is a series of brilliant, horrible hacks that enable you to expose the kinds of higher level custom properties that conditionals typically enable.
One technique that hurts my brain to think about is what Jane Ori called “type grinding” a few years ago. The idea is that you daisy-chain multiple @property
declarations to change the value of a CSS variable as it passes through them. Which makes for a wild, mind-bending read.
I had never heard of this exciting contrast-color
function before:
.element {
background: var(--bg-color);
color: contrast-color(var(--bg-color));
}
That’s from Lea Verou’s great piece about generating text colors. The way it works is that you pass a background color into the function and it’ll spit out a color that’s accessible to read as text on top of it. This solves about 90% of the problems I have with working with colors today as it’s super frustrating to constantly redefine variables or create new ones, just when the design calls for the background to change.
It might be a bit of a wait until it lands in browsers though, as Lea writes:
Glorious, isn’t it? Of course, soonish in spec years is still, well, years. As a data point, you can see in my past spec work that with a bit of luck (and browser interest), it can take as little as 2 years to get a feature shipped across all major browsers after it’s been specced. When the standards work is also well-funded, there have even been cases where a feature went from conception to baseline in 2 years, with Cascade Layers being the poster child for this: proposal by Miriam in Oct 2019, shipped in every major browser by Mar 2022. But 2 years is still a long time (and there are no guarantees it won’t be longer). What is our recourse until then?
Lea then talks about how it’s possible to set the color of text based on its background today with the relative color syntax. Super smart stuff.