Sass provide darken and lighten mixins to make our colors looks darken or lighten, but how to do it without a preprocessor, only with the power of CSS ?
We will learn how to use hsl and calc) functions to build darken and light colors.
Demo
Feel free to see the Final
Our goals
- How to use HSL for colors.
- Using the calc function.
Colors in HSL.
To begin, we want 3 version of red company color, the hex version is #ff0000
, and taking it as reference how I can change it ? The HSL come to help us.
The HSL() help us to define a color according to its hue, saturation, and lightness, so the red #ff0000 and converting it to HSL the result is hsl(0, 100%, 50%).
[How to conver hex to hsl] (htmlcolors.com/hex-to-hsl)
We can use hsl(0, 100%, 50%) to create the company red color and store it into the variable.
--color-company-red: hsl(0, 100%, 50%);
It works, but how can I change the light or darken ? First split the color values, and use hsl function to create it again.
--color-company-red-h: 0;
--color-company-red-s: 100%;
--color-company-red-l: 50%;
/* using hsl create the default red*/
--color-company-red: hsl(var(--color-company-red-h), var(--color-company-red-s), var(--color-company-red-l));
Perfect, first step complete, we have the default red color.
Using calc function for darken and light.
Now that you’ve been decouple the red color, we use the calc CSS function to change the value of light.
The calc() CSS function lets us perform calculations in values example (eg: width: calc( 3 + 100px));
).
Using the calc function with + or - operator over the CSS custom property --color-company-red-l
, we can reduce or increase, the light so, with less light is dark and more is lightened.
/* light version*/
--color-company-red-light: hsl(
var(--color-company-red-h),
var(--color-company-red-s),
calc(var(--color-company-red-l) + 15%)
);
/* dark version*/
--color-company-red-darken: hsl(
var(--color-company-red-h),
var(--color-company-red-s),
calc(var(--color-company-red-l) - 25%)
);
It’s time, use the colors and to override to using the red color versions.
/* Every class override the value of --box-bg with the version of red color */
.red {
--box-bg: var(--color-company-red);
}
.red-light {
--box-bg: var(--color-company-red-light);
}
.red-darken {
--box-bg: var(--color-company-red-darken);
}
.box {
background: var(--box-bg);
}
#The demo
Done! We have the darker and lighten based of our red company color without any preprocessor.
{% stackblitz css-custom-properties-darken-lighten %}