Advertisement


Choose white or black letters over color


Question

Given a background color, what is the best way to determine if I should use black or white for the foreground color?

For example, could I use a formula based on the HSB values of the color?

It's for an app in which the background color is dynamic.

2014/02/10
1
3
2/10/2014 4:33:00 PM

I have used a javscript based color picker on some of my sites, and the font color within the input box changes based on the values the picker chooses...

enter image description here

The code (Direct Code Link Here) for the script shows a specific location for the colorization of the input box the script is attached to.

Within that code you can see the formula:

0.213 * this.rgb[ 0 ] +
0.715 * this.rgb[ 1 ] +
0.072 * this.rgb[ 2 ]

With the result being:

< 0.5 ? '#FFF' : '#000';

or... (IF) less than 0.5 of the pure white (255) = 'White' (Otherwise) = 'Black';

enter image description here

You can extrapolate from that formula that: 0.213 * your RED value (0 - 255) +
0.715 * your Blue Value (0 - 255) +
0.072 * your Green value (0 - 255)
gives you a number

...and if that number is greater than .5,

you should opt for a Black font color, otherwise, go for white.

Example:

enter image description here

0.213 * 21 = 4.473
0.715 * 57 = 33.605
0.072 * 117 = 8.424

4.473 + 33.605 + 8.424 = 46.502

Since 46.502 is less than .5 of the pure white (255), we should use white on this background.

Hope this helps.

2015/02/16
3
2/16/2015 6:49:00 PM