DEV Community

Cover image for Contrasting Color
Dale Stubbart
Dale Stubbart

Posted on

Contrasting Color

javascript hashtag#colors

I searched for an easy way fo find the best contrasting color for colors on my website.
There's contrast-color in css, but only works in Firefox and Safari.
There are other options with limited availability.
I didn't see any formula's I liked.
Google Search AI offered steps. I'm hesitant to use anything AI offers without another source where I can verify it. The steps were written differently enough, that it took my brain a few minutes to understand what each one was saying and how they could/would work together.
In my xs_style.js library which would be open source, but I'm the only one maintaining it, I used those steps to build xs_color_contrast_enhanced. It allows you to contrast with the best of 2, 3, or 4 colors. It also allows you to contrast with the best of any number of colors - just pass them in an array. Yes, it can do 16777216 colors, which is the max # colors available on a website. But, you're array of colors should probably be much smaller for performance sake.
xs_style.js contains xs_color_rainbow_array and that worked best for contrast.
However, there were still a few colors on my Many Colors page where the contrast/text color was off - see link at bottom of post. There, I display about 1000 colors. There's another array which also has white and black, besides rainbow colors. That one was further off. Mostly some greens should have had white/light text and some reds should have had black/dark text. I added a couple of arrays to that webpage so that I could overwrite the contrasting colors that were visually off. Until I get a contrast formula that's closer, this will have to do. Only 114 were off. Not bad. Perhaps, I could have checked the hue colors to see if they were red or green. But, that would have corrected too many incorrectly. And there were more colors where the contrasting color was off.
I thought that if I evenly spaced the colors throughout the possibilities, that might work. Maybe it would if they were evenly spaced by luminosity, but by hex value it didn't help.
Still, since it would be close in most situations, I added it to my webpage where you can input a color and find out the closest official colors. You can also find that page at the following link.
https://stubbart.com/computer_consulting/color_themes/color_all.html
If you know of better ways to find the contrasting color, please let me know. And, always feel free to ask questions.

Top comments (0)