← Blog

contrast-color() picks the text colour

The buttons on this site can be tinted to any colour from the admin page. Working out whether the writing on top should be black or white was a small pile of maths.

The buttons here can be tinted from the admin page. Whatever colour gets picked, the writing on top has to stay readable.

That sounds like nothing, and it isn't, because how bright a colour looks to us has surprisingly little to do with how much of it there is. Green reads as much brighter than blue at the same strength. So you can't add the three channels up and take an average. There's a proper sum for it that weights each one differently, and I'd guess most of us have copied it off the same page on the internet.

The fix...

CSS does it now.

color: contrast-color(var(--tint));

The browser reads the background and hands back black or white, whichever is easier to read on it.

Black or white is all it offers, so if you had your heart set on a dark navy you're back to doing the sum. For a button whose colour is somebody else's decision, black or white is the right answer anyway.

Every browser has had it since April.

If any of it is useful on your project, say so.