Change text color based on brightness of the covered background area?

Change text color based on brightness of the covered background area?

I’ve thought about the following for a while already, so now I want to know your opinions, possible solutions, and so on.
I am looking for a plugin or technique that changes a text’s color or switches between predefined images/icons depending on the average brightness of the covered pixels of it’s parent’s background-image or -color.
If the covered area of it’s background is rather dark, make the text white or switch the icons.
Additionally, it’d be great if the script would notice if the parent has no defined background-color or -image and then continue to search for the most nearest (from parent element to it’s parent element..).
What do you think, know about this idea? Is there something similar out there already? script-examples?
Cheers, J.


Solution 1:

Interesting resources for this:

Here’s the W3C algorithm (with JSFiddle demo too):

var rgb = [255, 0, 0];

// randomly change to showcase updates
setInterval(setContrast, 1000);

function setContrast() {
  // randomly update
  rgb[0] = Math.round(Math.random() * 255);
  rgb[1] = Math.round(Math.random() * 255);
  rgb[2] = Math.round(Math.random() * 255);

  var o = Math.round(((parseInt(rgb[0]) * 299) +
                      (parseInt(rgb[1]) * 587) +
                      (parseInt(rgb[2]) * 114)) / 1000);
  var fore = (o > 125) ? 'black' : 'white';
  var back = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
  $('#bg').css('color', fore); 
  $('#bg').css('background-color', back);

#bg {
  width: 200px;
  height: 50px;
<script src=""></script>

<div id="bg">Text Example</div>

Solution 2:

This article on 24 ways about Calculating Color Contrast might be of interest to you. Ignore the first set of functions because they’re wrong, but the YIQ formula will help you determine whether or not to use a light or dark foreground color.

Once you obtain the element’s (or ancestor’s) background color, you can use this function from the article to determine a suitable foreground color:

function getContrastYIQ(hexcolor){
    hexcolor = hexcolor.replace("#", "");
    var r = parseInt(hexcolor.substr(0,2),16);
    var g = parseInt(hexcolor.substr(2,2),16);
    var b = parseInt(hexcolor.substr(4,2),16);
    var yiq = ((r*299)+(g*587)+(b*114))/1000;
    return (yiq >= 128) ? 'black' : 'white';

Solution 3:

Interesting question. My immediate thought was to invert the color of the background as the text. This involves simply parsing the background and inverting its RGB value.

Something like this:

var rgb = $('#test').css('backgroundColor');
var colors = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var brightness = 1;

var r = colors[1];
var g = colors[2];
var b = colors[3];

var ir = Math.floor((255-r)*brightness);
var ig = Math.floor((255-g)*brightness);
var ib = Math.floor((255-b)*brightness);

$('#test').css('color', 'rgb('+ir+','+ig+','+ib+')');

Solution 4:

I’ve found the BackgroundCheck script to be very useful.

It detects the overal brightness of the background (be it a background image or a color), and applies a class to the assigned text-element (background--light or background--dark), dependent on the brightness of the background.

It can be applied to still and moving elements.


Solution 5:

mix-blend-mode does the trick:

header {
  overflow: hidden;
  height: 100vh;
  background: url( 50%/cover;

h2 {
  color: white;
  font: 900 35vmin/50vh arial;
  text-align: center;
  mix-blend-mode: difference;
  filter: drop-shadow(0.05em 0.05em orange);
  <h2 contentEditable role='textbox' aria-multiline='true' >Edit me here</h2>

Addition (March 2018):
Following, a nice tutorial explaining all different types of modes/implementations:

Solution 6:

Here’s my attempt:

(function ($) {
    $.fn.contrastingText = function () {
        var el = this,
        transparent = function (c) {
            var m = c.match(/[0-9]+/g);
            if (m !== null) {
                return !!m[3];
            else return false;
        while (transparent(el.css('background-color'))) {
            el = el.parent();
        parts = el.css('background-color').match(/[0-9]+/g);
        this.lightBackground = !!Math.round(
                parseInt(parts[0], 10) + // red
                parseInt(parts[1], 10) + // green
                parseInt(parts[2], 10) // blue
            ) / 765 // 255 * 3, so that we avg, then normalise to 1
        if (this.lightBackground) {
            this.css('color', 'black');
        } else {
            this.css('color', 'white');
        return this;

Then to use it:

var t = $('#my-el');

This will straight away, make the text either black or white as appropriate. To do the icons:

if (t.lightBackground) {
    iconSuffix = 'black';
} else {
    iconSuffix = 'white';

Then each icon could look like 'save' + iconSuffix + '.jpg'.

Note that this won’t work where any container overflows its parent (for example, if the CSS height is 0, and overflow isn’t hidden). To get that working would be a lot more complex.