Skip to content

Instantly share code, notes, and snippets.

@ameliabradley
Last active January 5, 2017 21:20
Show Gist options
  • Save ameliabradley/c967b0c2d896abef66c74ed14a170169 to your computer and use it in GitHub Desktop.
Save ameliabradley/c967b0c2d896abef66c74ed14a170169 to your computer and use it in GitHub Desktop.
Given a hex color, finds the optimal font color (black or white)
function getFontColorFromBackgroundColor (bgColor) {
if (!bgColor.match(/#[0-9a-z]{6}/i)) {
return 'white';
}
const [r, g, b] = [1, 3, 5].map((o) => parseInt(bgColor.slice(o, o + 2), 16));
const greyscale = (0.2125 * r) + (0.7154 * g) + (0.0721 * b);
return (greyscale > 127) ? 'black' : 'white';
}
@ameliabradley
Copy link
Author

ameliabradley commented Jan 5, 2017

JavaScript function that takes any background color and produces the most readable, legible font color.

Inspired by Mark Ransom's answer on StackOverflow.

For maximum legibility, you want maximum brightness contrast without getting into hues which don't work together. The most consistent way to do this is to stick with black or white for the text color. You might be able to come up with more aesthetically pleasing schemes, but none of them will be more legible.

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