Text/background colour determination

Hi folks!

A quick technical question - hope this is still the right place to post them.

How can I determine whether an arbitary background colour (expressed in standard #xxxxxx RGB format) requires white or black text?

I’ve tried to come up with a solution to this in the past but have never found one, because “looks good on white” and “looks good on black” does not seem to follow any pattern on the hex color chart (btw RGB = 000,000,000, hex = #000000)

You might just need to use a chart like this and switch bg colors and make your own database table to store the data as to what is readable on what color background.

You know that “hex” is still RGB values, right? :wink:

Anyway, I think it’s pretty reasonable to just use a simple heuristic like: use black if the R, G and B average to a number > 127, and use white if they don’t. It’s pretty simple. I’m sure there are some cases where color perception theory will give you a different answer, but this method definitely won’t result in text you can’t see. Here’s a little test I did:

http://sdmbexample.nfshost.com/color/

Drag the color dot around to change the text color and watch the background of the big block of text flip back and forth between white background and black background.

BTW, one thing this experiment does prove is that it’s hard to read text with changing color and flip-flopping background colors. :slight_smile:

Missed the edit window, but I just noticed that that YUI color picker control doesn’t look very nice in IE. Whoops. Try it in firefox for best results.

Yikes, and after all that, I see I answered the opposite question from the one you were asking (you wanted white or black text on an arbitrary color and I did arbitrary-colored text on a white or black background). The answer oughta be the same. I’ll make a test for that too. Hang on.

Hey nice work! I will have to remember that > 127 figure in the future - it’s better than nothing!

And yeah I know what hex and RGB are :wink:

here you go

Thanks very much indeed, just what I was looking for.

(Incidentally, this may be obvious, but I think I should mention it - you just need to test that the total of R, G, and B is less than 381, there’s no need to actually calculate the average for this particular purpose).