{"id":339318,"date":"2021-04-26T14:02:49","date_gmt":"2021-04-26T21:02:49","guid":{"rendered":"https:\/\/css-tricks.com\/?p=339318"},"modified":"2021-04-27T16:04:58","modified_gmt":"2021-04-27T23:04:58","slug":"exploring-color-contrast-for-the-first-time","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/exploring-color-contrast-for-the-first-time\/","title":{"rendered":"Exploring color-contrast() for the First Time"},"content":{"rendered":"\n

I saw in the release notes for Safari Technical Preview 122<\/a> that it has support for a color-contrast()<\/code> function in CSS. Safari is first out of the gate here. As far as I know, no other browser supports this yet and I have no idea when stable Safari will ship it, or if any other browser ever will. But! It’s a very good idea! Any native tool to get us to ship more accessible interfaces (of which color contrast is a part) is cool by me. So let’s attempt to get it to work.<\/p>\n\n\n\n\n\n\n\n

\"\"<\/figure><\/div>\n\n\n\n

Anybody can download Safari Technical Preview<\/a>, so I did that. <\/p>\n\n\n\n

I had to ask around about this, but just because this is a pre-release browser, it doesn’t mean all these features are active by default. Just as Chrome Canary has feature flags you have to turn on, so does Safari Technical Preview. So, I had to flip it on like this:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n\n

The release notes don’t have any information about how to actually use color-contrast()<\/code>, but fortunately web searching turns up a spec (it’s part of Color Module 5<\/a>), and MDN has a page for it<\/a> with very basic syntax information. <\/p>\n\n\n\n

This is how I understand it:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n\n

That example above is a little silly, because it will always return white<\/code>\u2009\u2014\u2009that has the most contrast with black<\/code>. This function actually gets useful when one or more of those color values is dynamic<\/em>, meaning very likely it is a CSS custom property.<\/p>\n\n\n\n

The function returns a color, so the top use-case, I would guess, is going to be setting a color based on a dynamic background. So…<\/p>\n\n\n\n

section {\n  background: var(--bg);\n  color: color-contrast(var(--bg) vs white, black);\n}<\/code><\/pre>\n\n\n\n

Now we can toss any color at all<\/strong> at --bg<\/code> and we’ll either get white or black text, depending on what has the most contrast:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n\n

That’s extremely cool<\/a>, even in the most basic use case.<\/p>\n\n\n\n

Here’s a demo from Dave where he’s not just setting the text color in the parent, but the color of links as well, and the links have a different set of colors to choose from. Play with the HSL sliders (in Safari Technology Preview, of course) to see it work.<\/p>\n\n\n\n