JavaScript color contraster

Julien Genestoux picture Julien Genestoux · Apr 13, 2011 · Viewed 11.3k times · Source

I'm looking for a technique where we could programmatically pick the best color contrast to apply on text over HTML elements of different (unpredictable) background colors.

Since the HTML elements will have different colors, we're looking for a technique that will be able to determine what is the color of the content behind the text, and then adapt the text's color to use the one with the best contrast.

I'm quite sure this can't be CSS only, I've looked for Jquery solutions but couldn't find any... anyone has a clue?

[UPDATE] : Based on the first replies, I guess I need to rephrase. Imagine that I'm building a image sharing service and I want to allow people to tag on the pictures themselves. The pictures can be of any color. How can I pick up the right color of the tags, for each different picture?

Answer

Alex Marchant picture Alex Marchant · Mar 12, 2012

I think this might save any future researchers a little time, this works perfectly for me. Plug in the red green and blue values into the function and it outputs "dark-text" or "light-text".

var darkOrLight = function(red, green, blue) {
  var brightness;
  brightness = (red * 299) + (green * 587) + (blue * 114);
  brightness = brightness / 255000;

  // values range from 0 to 1
  // anything greater than 0.5 should be bright enough for dark text
  if (brightness >= 0.5) {
    return "dark-text";
  } else {
    return "light-text";
  }
}

Using some code from http://particletree.com/notebook/calculating-color-contrast-for-legible-text/ from @David's answer.