Skip to content

Instantly share code, notes, and snippets.

@Androguide
Last active September 4, 2015 15:33
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 Androguide/73f811f606cda2d361cd to your computer and use it in GitHub Desktop.
Save Androguide/73f811f606cda2d361cd to your computer and use it in GitHub Desktop.
Get black or white color depending on background color for best readability. Based on the YIQ color-space contrast ratio.
function blackOrWhite(hexcolor) {
var color = hexcolor.substring(1);
hexcolor = color.length < 5 ? color + color : color;
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 >= 125) ? '#333' : '#eee';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment