Skip to main content

Tagged with

Generating text colors

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.

Hints and Suggestions

Miriam Suzanne gave a fantastic talk the other day during 11ty’s International Symposium on Making Web Sites Real Good and I couldn’t possibly recommend it more. The highlight for me was when Miriam talks about the “CSS is awesome” meme:

This is the reason that the default overflow is visible: if we get cocky and make a box too small for our text, browsers will try to bail us out. Not because it’s the best looking solution but because the web will try to protect content whenever it can. Browsers are helping us out here.

So to me, this meme, this “CSS is awesome” box-breaking meme, it actually perfectly captures what is awesome about CSS and how much can go wrong when we try to control things that we shouldn’t necessarily control. When we add too many constraints at once.

I love that meme for the wrong reasons.

Miriam argues that this is a core part of CSS’s design but it’s also a political choice: to protect the content and protect the user we shouldn’t treat the CSS we write as a series of strict rules. Instead, we must think of them as hints and suggestions to the browser. Or, as Miriam says: guidance with a light touch.