18

I'm looking for a way, with jQuery ideally, to determine the correct text color, based on the brightness of the background color?

E.g. white background, black text colour. I believe this could be done crudely with adding the HEX value and guesstimating but does anyone know a better way or jQuery way to do this?

waxical
  • 3,826
  • 8
  • 45
  • 69
  • and what with gray (#808080) ? – gertas Jan 18 '11 at 16:23
  • Possible duplicate of [How to decide font color in white or black depending on background color?](https://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color) – user Aug 20 '17 at 01:42

2 Answers2

42

You can try inverting the hex value of the color. So #FFFFFF becomes #000000 and #AAAAAA becomes #555555. Of course, this method falls through when you have #888888 which when inverted, gives you #777777 (they don't contrast as much).

This blog post describes another way (they only use black or white for the foreground color, depending on the background color). I've translated it into Javascript:

function idealTextColor(bgColor) {

   var nThreshold = 105;
   var components = getRGBComponents(bgColor);
   var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);

   return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";   
}

function getRGBComponents(color) {       

    var r = color.substring(1, 3);
    var g = color.substring(3, 5);
    var b = color.substring(5, 7);

    return {
       R: parseInt(r, 16),
       G: parseInt(g, 16),
       B: parseInt(b, 16)
    };
}
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • Thanks for this informative answer, I'm just having a look at your suggested code translation and I'm getting "missing ; before statement [Break On This Error] int bgDelta = (components.R * 0.2...mponents.G * 0.587) + (bg.B * 0.114);" - however I can't see that missing ;? does it work for you? – waxical Jan 18 '11 at 16:51
  • @WiseDonkey Oops, I've updated it. When I was translating, I forgot to change a `bg` into `components`, an `int` into `var`, and I used semicolons instead of commas in `getRGBComponents`. – Vivin Paliath Jan 18 '11 at 17:01
  • 1
    const idealTextColor = ([a, b, c]: number[]) => (150 < (a * 0.299) + (b * 0.587) + (c * 0.114)) ? "black" : "white"; – Corey Alix Feb 23 '17 at 04:58
0

If you use Typescript you can use this function:

setFontColor(bgColor){
  let r = bgColor.substring(1, 3);
  let g = bgColor.substring(3, 5);
  let b = bgColor.substring(5, 7);

  const bgDelta = (parseInt(r, 16) * 0.299) + (parseInt(g, 16) * 0.587) + (parseInt(b, 16) * 0.114);
  return ((255 - bgDelta) < 105) ? "#000" : "#fff"; }

In the HTML (Like Angular):

<div class="color-bg" [style.color]="true? setFontColor(color) : '#000'">
    your text
</div> 

My result:

enter image description here

Avi
  • 117
  • 1
  • 6