Skip to content

Instantly share code, notes, and snippets.

@artyom-ivanov
Created February 1, 2022 19:46
Show Gist options
  • Save artyom-ivanov/bd4ee0cb192c851ad558aa58c80b28d8 to your computer and use it in GitHub Desktop.
Save artyom-ivanov/bd4ee0cb192c851ad558aa58c80b28d8 to your computer and use it in GitHub Desktop.
Detect text color for good contrast with background
export function textColorForBackground(hexColor: string): 'white' | 'black' {
let hex = hexColor.replace('#', '');
let r = parseInt(hex.substr(0, 2), 16);
let g = parseInt(hex.substr(2, 2), 16);
let b = parseInt(hex.substr(4, 2), 16);
let brightness = (r * 299 + g * 587 + b * 114) / 1000;
return brightness > 155 ? 'black' : 'white';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment