Calculate Text Color Based on Background Color Brightness

I created a site a while back that had a table of data with a column that contained the status of each row. The status was color-coded : red for bad, light green for good, black for deleted, yellow for average etc. The problem I had was that the text color could not be seen for the darker background colors, because it was black. The solution was to use a formula to calculate the brightness of the background color and based on that value, change the text color to either white or black. The code was actually very easy to do, and here it is in C#:

Then the other day I saw that this was a priority requirement for the Launch Effect theme:

So I thought it would be a good exercise to try and do the same thing in jQuery and PHP. So that is what I did. And below are my findings.

First, The Theory Behind It

My original C# code was written with the help of an article written by Darel Rex Finley named HSP Color Model . Basically, the trick is to take the Hex color code (#336699 or #FFAA32 etc) and break it up into it’s RGB components : red, green and blue. Once you have that then you calculate a “brightness indicator” using this formula:

brightness  =  sqrt( .299 R2 + .587 G2 + .114 B2 )

The result is a number from 0 to 255. And then you simply use white text if that value is below 130 or otherwise you use black text. Simple

The Solution Using jQuery

This can also be done completely on the client side using some javascript. First, I needed some code to parse the hex color into it’s RGB components. I found this really awesome (and free) script RGB color parser which also understands English colors as well as hex colors. So you can use colors like “light green” instead of “#88FF88″.

The Solution Using PHP

This turned out to be pretty simple in PHP too. Again, all I needed was a nice helper function to convert my hex color into an array of the red, green and blue intensities.

Hopefully this can help someone out there. If not, it was fun to put together in any case