Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Aug 4, 2015

Cool.

@wonjun27

This comment has been minimized.

Copy link

commented Apr 7, 2016

Cool

@EnricoVogt

This comment has been minimized.

Copy link

commented Apr 20, 2017

Thanks ;)

@zivoradmilekic

This comment has been minimized.

Copy link

commented Mar 31, 2018

Thanks man ;)

@nizewest

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.