How to have the browser pick a contrasting color in CSS
75 comments
·May 17, 2025qfr
there is a way to do something close to this using lch:
--text: lch(from var(--bg) calc((49.44 - l) * infinity) 0 0);
source: https://til.jakelazaroff.com/css/swap-between-black-and-whit...sabellito
LCH is awesome but OKLCH is even better!
https://evilmartians.com/chronicles/oklch-in-css-why-quit-rg...
Can honestly say this article changed my perspective on this subject drastically, such an amazing tool. I was very surprised that my designer friends hadn't heard of oklch at all, it solves a whole category of problems.
natemwilson
I’ve never seen any CSS function that has this call back style where you get parameters that you can modify. So interesting! Are there any other examples of this or is this unique to lch?
fireflies_
This is "relative color" syntax, it works with a range of color spaces/color functions. The key is the "from" at the front. Here's the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_colors/...
halflife
It may be confusing, but everything here is static param. The —- prefix is css variables, where inside a css declaration block you write: —bg: blue
natemwilson
The `l` isn't!
KTibow
Some newer ones like calc-size are also like this.
LorenzA
there is a good article from lea verou https://lea.verou.me/blog/2024/contrast-color/ on a workaround like this
mediumsmart
I will trust you on that since I did see the page load before it turned white on this phone browser combination.
jjcm
This is a great overview of the pros/cons of this. For those creating just a simple site, this is a solid easy way to have proper contrast.
For those making anything at a production scale where you need wcag compliance however, I'd avoid this and leverage a proper semantic token layer. Semantic tokens will help both accelerate your dev cycle, and they'll help guarantee proper contrast ratios in a way that looks visually better than just switching your foreground layer to black or white. The great thing about a semantic token layer is they're extremely easy to theme, which means you get light/dark theming for very little additional cost. You can also create separate WCAG2 / APCA accessible themes, should your brand color be one of the ones that WCAG2 has issues with - will get you compliance while still providing a better visual contrast option.
This is kind of my niche domain specialty - I run the variables/tokens stream at Figma, and I've worked on the dark mode implentation for both Figma and Atlassian. Happy to answer any questions about tokens/themes/accessible color.
charrondev
What do you mean by semantic tokens?
This exact type of functionality has caused a major project a work on to use CSS in JS (for relative colors and contrast colors.
I’m glad to see this type of thing coming around the corner and look forward to it being widely available in a couple years.
jjcm
With regards to color on the web, semantic tokens refer to css variables that are named in a way that describes their use, ie:
* bg-brand (this would be used whenever you need your brand color as a background)
* text-danger (likely a red text color)
* icon-warning-hover (likely a dark yellow-orange that's slightly different from icon-warning)
Generally speaking, there are three "levels" of tokens: primitive, semantic, and component. Primitive tokens describe the value. In the case of color, this might be a color ramp. IE red/100, red/200, red/300. Semantic tokens reference primitive tokens. IE bg-brand might have its value set to blue/300. This layer is sometimes called a "reference" layer because of this, but I'm not a fan of that nomenclature since the component layer also references the semantic layer. The component layer is one that describes where in a component the token should be used, ie button-bg or button-text. I highly, HIGHLY recommend against using a component layer though in all but the most extreme multi-brand situation. If you aren't unilever, you should never use component tokens.
ZYbCRq22HbJ2y7
Aren't there many, many schemes for naming tokens in design systems? Aren't you being a bit forward in presenting this as a general practice?
https://medium.com/eightshapes-llc/naming-tokens-in-design-s...
recroad
This only works if you don’t let users theme your site. If you do, then OPs approach works better.
hk1337
I don’t disagree, in fact I absolutely agree but the last 2/3 just sounds like meaningless jibber jabber to make yourself look smart. I’m not saying it’s not true but it’s word vomit.
I like the feature but in a corporate site/application, you don’t want to rely on this function because you cannot control what the result is going to be. For all I know, WebKit could fix some later bug or change something that changes the result color to something that I don’t want.
throwaway290
If you don't understand something it doesn't always make that a word vomit:)
mediumsmart
>But, on a large project, with a large team, carefully managing such details can become a really hard task to get right. Suddenly a dark button has unreadable black text, and users can’t figure out what to do.
Cant someone take a look at the buttons before the large project ships? Alternatively make it mandatory to never have black text on a dark button and tell every team member including the large ones.
Interesting to read about the perceptual contrast vs mathematical - I did not know that. Going to integrate that into my workflow.
Merad
> Cant someone take a look at the buttons before the large project ships?
They can, of course, but this is how you end up with pre-release regression testing cycles that are weeks or even months long. A "large project" might easily have thousands of buttons (or more!), many of which are only seen when certain settings are enabled, certain options are chosen during a complex workflow, etc.
johnisgood
You may want to read about APCA, as you can have perceptual contrast calculations using the APCA algorithm.
refulgentis
You can have them with WCAG2, the stock APCA example hides the ball significantly and leads to a lot of incorrect conclusions in the article (tl;dr: black has more contrast by either measure, its just that APCA says you don't need as much contrast, so you can use white and have sufficient contrast)
johnisgood
I know about WCAG, too. You can also just implement a function that detects whether or not a color is dark or not. It is a general purpose function, e.g. my "isDark" function is: "func() < 0.5" (func() is omitted, but it is an algorithm). You can have "isLight", too, by doing "> 0.5". There are many ways to do this. You can just simply convert a hex color to RGB, then compute the luminance of the color, and then compare the luminance to a threshold (e.g. 0.5) to classify it as dark or light. The luminance function (WCAG luminance formula) converts RGB values to the range 0-1, applies gamma correction, and calculates luminance using the weighted sum of the gamma-corrected RGB values.
> APCA says you don't need as much contrast
You can always specify the threshold if you want, e.g. "apcaContrast(color)) >= $targetContrast" after adjusting, depending on what you want to do.
It really is easy, just make sure you have enough color space.
csande17
> black has more contrast by either measure
No it doesn't? The screenshot of the calculator in the blog post very clearly shows that white has a greater contrast according to APCA. (If the negative numbers are confusing, you can also put the colors into a BridgePCA calculator like https://www.color-contrast.dev/?txtColor=FFFFFF&bgColor=317C... to see WCAG-2-style "contrast ratio" metrics computed using APCA.)
The point of APCA is to make the contrast calculation more perceptually accurate, not just lower the threshold.
mediumsmart
I thought the white looks sharper but is not really. I would darken the blue a bit to be happy about it.
politelemon
I'm still not convinced that the contrasting colour should be the browser vendor's decision, it won't always be right or predictable. Will this be a definitive deterministic standard across all browsers? Instead this function feels like a tool to help UX teams during design phase.
MBCook
> Will this be a definitive deterministic standard across all browsers?
The article says the standard specifies the calculation to use.
andix
I'm already feeling some issues with HDR displays, embedded devices, and other special cases. The standard Safari on macOS/iOS and chrome on Windows/Linux/Android are probably going to handle it correctly. But I'm very happy if proven wrong :)
mcfedr
Choose is a strange word here. There is an algorithm that calculates the color.
refulgentis
c.f. https://news.ycombinator.com/item?id=44015980, when you cut out the incorrect stuff due to confusion re: APCA's button example, it's a bit clearer that it's 100% right.
Consistent, it is not. Ex. we can imagine a background at L* 50 that is ~equally served with a white or black foreground - in that case, the aesthetic principles come into play.
To also disambiguate that, and get to 100% reliable, if both a darker and lighter color are available given contrast K and background color C, look at C, if it's L* is >= 60, choose lighter.
Then, it is 100% correct and consistent.
econ
Back when systeem colors were actually cool I made some system color styles. It looked really nice but you don't know how they contrast. That one is called [say] buttonFace and another buttonText turned out to to be meaningless. Someone wrote some js for me that took getComputedStyle and calculated the contrast. If it was unacceptable it either took a second candidate color or failed back on text-shadow to darken or lighten an aura around the text sufficiently.
https://i.sstatic.net/18bQt.png
I forget the calculation but thinking about it you can probably just take the average of the 3 rgb values and compare them(?) It would produce a low value for blue and give preference to white text.
econ
Hotlinking didn't work.
https://www.freepik.com/free-vector/white-3d-editable-vector...
jbritton
At a minimum it would be nice to know good colors for the pseudo classes active, focus, hover, link, visited and their various combinations for a light and dark theme. Additionally material UI adds disabled, before, after.
atum47
I made a video tutorial about a similar thing long time ago - choosing black or white for text color given a color background. My solution was very simplistic. I just transformed the color to gray scale and compared it between black and white. It was a fun project. I'm not good making videos though.
https://youtu.be/tUJvE4xfTgo?si=vFlegFA_7lzijfSR (warning: video is in Portuguese)
coolcase
Funny a sister comment gave a color space formula to do just that
https://news.ycombinator.com/item?id=44015990
Video seems fine. I don't speak Portuguese though so can't judge what you said but code looks good!
atum47
Appreciate it
rendaw
You choose all the colors in a color scheme, so why is this easier than just choosing a contrasting button text color in the first place? This is a feature to help teams so dysfunctional that individuals are free to choose an inconsistent background color yet at the same time aren't able to choose a contrasting foreground color?
What really needs a fix is when you have text over an image or other diverse background (like, sticky/fixed text over a scrolling background) and need to have it always visible. And... this doesn't help at all.
So not only does this only (maybe) help in very questionable circumstances, they needed to come up with an entirely new verb for it, it has an anemic feature set (only selects black or white), and they did it with the worst possible contrast selection algorithm (doesn't select the choice with the most perceptual contrast). Way to go!
healsdata
Its limiting to dismiss a tool out of hand simply because you haven't encountered a situation where that tool would be useful.
Plenty of web sites allow the end-user to select colors[1], or automatically derive colors from assets provided by the end-user. For those that care about accessibility, they typically calculate contrasting colors to prevent the user from creating a non-accessible experience. A built-in CSS tool like this will, hopefully, encourage more sites to provide a basic amount of accessibility while in no way hindering those who want to build an even better experience.
It would be cool if this was more customizable like the npm contrast-color package but the blog post details why they started with white/black with intentions of changing the algorithm later.
[1] Example: https://coolors.co/8fbfe0-7c77b9-1d8a99-0bc9cd-14fff7
ctxc
Yep. A simple use case I had was letting users create "tags" and choose their own color for the chips (think Github PR tags like "good-first-issue" "bugs" but custom)
I'm surprised parent hasn't come across this usage, I see it everywhere.
ezfe
> and they did it with the worst possible contrast selection algorithm
They specifically say they are following WCAG 2 algorithms, and that WCAG 3 may correct this issue. They say that they can easily adjust to use the better algorithm in the future when it's standardized.
andix
Is there a good alternative for this that is done at build time? Something that works on top of SASS, Tailwind, etc?
It will take some time until this feature is broadly available, and I'm having some doubt that it will be implemented in the same (or correct) way on all platforms.
ZYbCRq22HbJ2y7
Tentative future of this feature, that addresses many concerns in this thread:
akkartik
Recently I made a little hypertext browser in 500 lines. Then I added this sort of automatic contrasting color selector in another 200 lines. In the process I learned a lot about color spaces.
https://akkartik.name/post/2025-04-04-devlog
One difference in my approach is: it's an authoring-time tool. If no sufficiently contrasting color exists you get an error. And so you have to change the background until there is one.
For this problem, I'm working on a tool to help create palettes where color pairs have simple and predictable WCAG/ACPA contrast by design (it has more features on desktop):
https://www.inclusivecolors.com/
So one approach is you create swatches of different colors that go from grade 100 (light) to grade 900 (dark), where the lightnesses are chosen such that all grade 700 colors contrast against grade 100 colors, all grade 800 colors contrast against grade 200 etc.
And then you know red-700 vs gray-100, green-800 vs yellow-200 and so on will contrast without having to check.
If you go to the Contrast menu, you can also explore how much stricter the APCA algorithm (meant to be more accurate) is compared to WCAG. For dark on light colors especially, APCA is much stricter about what contrast so you really shouldn't use WCAG for dark themes.
Also, if you go to the Examples menu and check out the Tailwind and IBM Carbon color palettes, you can see how the swatches in hand designed palettes vary their saturation and hue across grades in a non-linear way. So automatically picking if white/black contrasts the best is more straightforward (like the article mentions), but for more deliberate/branded palettes, you can't just generate a color with a simple lightness component shift, so this is more open ended.