My solution was transform HEX code color to HSL. First i've created a PHP Function.
function hexToHsl($hex) {
$hex = str_split(ltrim($hex, '#'), 2);
// convert the rgb values to the range 0-1
$rgb = array_map(function($part) {
return hexdec($part) / 255;
}, $hex);
// find the minimum and maximum values of r, g and b
$min = min($rgb);
$max = max($rgb);
// calculate the luminace value by adding the max and min values and divide by 2
$l = ($min + $max) / 2;
if ($max === $min) {
$h = $s = 0;
} else {
if ($l < 0.5) {
$s = ($max - $min) / ($max + $min);
} elseif ($l > 0.5) {
$s = ($max - $min) / (2 - $max - $min);
}
if ($max === $rgb[0]) {
$h = ($rgb[1]- $rgb[2]) / ($max -$min);
} elseif ($max === $rgb[1]) {
$h = 2 + ($rgb[2]- $rgb[0]) / ($max -$min);
} elseif ($max === $rgb[2]) {
$h = 4 + ($rgb[0]- $rgb[1]) / ($max -$min);
}
$h = $h * 60;
if ($h < 0) {
$h = $h + 360;
}
}
return array($h, $s*100, $l*100);
}
it will receive the hex code color por example #cc66cc and will return an array of 3 values for H, S and L.
$color_main_hsl = hexToHsl($color_main);
$color_main_h = $color_main_hsl[0];
$color_main_s = $color_main_hsl[1] . '%';
$color_main_l = $color_main_hsl[2] . '%';
And then assign to a variable CSS.
<style>
:root {
--color_1: <?php echo $color_main; ?>;
--color_1_h: <?php echo $color_main_h; ?>;
--color_1_s: <?php echo $color_main_s; ?>;
--color_1_l: <?php echo $color_main_l; ?>;
}
</style>
Then i create 2 functions in SASSS, 1 for darken and other for lighten:
// hsl css variable darken
@function hsl_d($color_num, $percentage) {
$color_h: var(--color_#{$color_num}_h);
$color_s: var(--color_#{$color_num}_s);
$color_l: var(--color_#{$color_num}_l);
@return hsl($color_h, $color_s, calc(#{$color_l} - #{$percentage}#{'%'}));
}
// hsl css variable lighten
@function hsl_l($color_num, $percentage) {
$color_h: var(--color_#{$color_num}_h);
$color_s: var(--color_#{$color_num}_s);
$color_l: var(--color_#{$color_num}_l);
@return hsl($color_h, $color_s, calc(#{$color_l} + #{$percentage}#{'%'}));
}
And finally I use my sass function:
.element-to-dark {
background-color: hsl_d(1, 12);
}
.element-to-light {
background-color: hsl_d(1, 22);
}
The number "1" is because my variables ara called --color_1, --color_1_h, --color_1_s, --color_1_l and my function interpolate this number. The second parameter is the percentage for light or darken.
I hope I have contributed :)