Skip to content

Instantly share code, notes, and snippets.

@jegtnes
Created June 6, 2013 08:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jegtnes/5720178 to your computer and use it in GitHub Desktop.
Save jegtnes/5720178 to your computer and use it in GitHub Desktop.
A function attempting to rudimentary replicate SASS lighten/darken functions. Adapted from Frxstrem's answer on StackOverflow: http://stackoverflow.com/questions/3512311/how-to-generate-lighter-darker-color-with-php
<?php
function sass_darken($hex, $percent) {
preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i', $hex, $primary_colors);
str_replace('%', '', $percent);
$color = "#";
for($i = 1; $i <= 3; $i++) {
$primary_colors[$i] = hexdec($primary_colors[$i]);
$primary_colors[$i] = round($primary_colors[$i] * (100-($percent*2))/100);
$color .= str_pad(dechex($primary_colors[$i]), 2, '0', STR_PAD_LEFT);
}
return $color;
}
function sass_lighten($hex, $percent) {
preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i', $hex, $primary_colors);
str_replace('%', '', $percent);
$color = "#";
for($i = 1; $i <= 3; $i++) {
$primary_colors[$i] = hexdec($primary_colors[$i]);
$primary_colors[$i] = round($primary_colors[$i] * (100+($percent*2))/100);
$color .= str_pad(dechex($primary_colors[$i]), 2, '0', STR_PAD_LEFT);
}
return $color;
}
?>
@rahularyan
Copy link

Cool.

@wonjun27
Copy link

wonjun27 commented Apr 7, 2016

Cool

@EnricoVogt
Copy link

Thanks ;)

@zivoradmilekic
Copy link

Thanks man ;)

@nizewest
Copy link

nizewest commented Apr 4, 2018

Thanks! I have found a little bug, new values must have limited like this:
$primary_colors[$i] = $primary_colors[$i] > 255 ? 255 : $primary_colors[$i];

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