Skip to content

Instantly share code, notes, and snippets.

@KimBranzell
Last active February 23, 2018 09:57
Show Gist options
  • Save KimBranzell/6992cb5fadffa94f2d78e45580f602bd to your computer and use it in GitHub Desktop.
Save KimBranzell/6992cb5fadffa94f2d78e45580f602bd to your computer and use it in GitHub Desktop.
Get Luminance from background color and adjust text-color thereafter
<?php
function getLuminance($val) {
$hex = $val;
// Get int RGB values from the hex.
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
// Calculate according to the formula
$red = 0.2126 * ($r/255);
$green = 0.7152 * ($g/255);
$blue = 0.0772 * ($b/255);
if ( $red + $green + $blue <= .5 ){
return 'light-text';
} else {
return 'dark-text';
}
}
?>
// Usage:
<div class="<?php echo getLuminance('#ffffff'); ?>"></div>
<div class="<?php echo getLuminance('#000000'); ?>"></div>
// Results in:
<div class="dark-text"></div>
<div class="light-text"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment