Skip to content

Instantly share code, notes, and snippets.

@hssm
Last active July 7, 2016 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hssm/7e24fbf9d01892d0f7a03d429bdc9ca3 to your computer and use it in GitHub Desktop.
Save hssm/7e24fbf9d01892d0f7a03d429bdc9ca3 to your computer and use it in GitHub Desktop.
A solution and demo for deciding if text should be black or white depending on the background color it is being placed on to guarantee readability.

Do you need a way to decide if text should be black or white depending on the background it is drawn on? This gist contains a simple and effective solution with a demonstration.

The color choice is calculated by hand-crafted rules derived by mere human inspection. Don't like how it works for a certain range? You can easily tweak the numbers for that range.

<html>
<head>
<meta charset="utf-8">
<style>
.box {
width: 55px;
height: 55px;
padding: 5px;
line-height: 1.8em;
text-align: center;
font-size: 14px;
font-weight: 700;
margin: 2px;
float: left;
}
.row { float: left; }
.play { font-size: 12px; }
</style>
<script>
function setColorByBackground(box) {
// Get RGB value and split it into the 3 components
var comp = getComputedStyle(box).backgroundColor.split("(")[1].split(")")[0].split(", ");
var r = parseInt(comp[0]);
var g = parseInt(comp[1]);
var b = parseInt(comp[2]);
box.style.color = "#000";
if (r+g < 170 || g+b < 300|| r+b < 400) {
box.style.color = "#fff";
}
if (r+g > 230 || g+b > 400 || r+b > 400) {
if (r+g < 190) {
// we made it white earlier - don't override it because it looks worse
} else {
box.style.color = "#000";
}
}
};
function drawBoxes() {
for (i = 0; i < 16; i++) {
group = document.createElement('div');
group.className = "group";
document.body.appendChild(group);
for (j = 0; j < 16; j++) {
row = document.createElement('div');
row.className = "row";
group.appendChild(row);
for (k = 0; k < 16; k++) {
var hexColor = "#" + i.toString(16) + j.toString(16) + k.toString(16);
box = document.createElement('div');
box.className = "box";
box.style.backgroundColor = hexColor;
box.innerHTML = hexColor + "<div class='play'>▶</div>";
row.appendChild(box);
setColorByBackground(box);
}
}
}
};
window.onload = function () {
drawBoxes();
};
</script>
</head>
<body>
</body>
</html>
@hssm
Copy link
Author

hssm commented Jul 7, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment