Build Dark and Light Color using HSL and Calc functions in CSS
You must know that Sass provides the darken and lighten mixins to display the colors looks darken or lighten, but have you ever wondered that how can we do that without any preprocessor i.e using only using CSS? To build this, we are going to use HSL and Calc() functions.
What is HSL?
HSL stands for hue, saturation, and lightness. The HSL() functional notation is used to express an RGB color in accord with its hue, saturation, and lightness components. The color values of HSL are supported mostly in Firefox, Chrome, Safari, and in Opera. HSL color values are specified with: the following.
hsl(hue, saturation, lightness)
- Hue is a degree on the wheel of color ranging from 0 to 360. Here, 0 is red, 120 is green, and 240 is blue.
- Saturation is a color percentage value in which 0% represents a shade of gray and 100% represents a full color.
- Lightness is also a percentage color value in which 0% is black, and 100% is white.
Calc(): The calc() function is from CSS which allows us to perform calculations when specifying CSS property values. This function can be used anywhere where a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed.
width: calc(100% - 80px);
Colors in HSL: To begin building, we require 3 versions of the “forestgreen” color and the hex version is #228B22 taking it as a reference how we can change it? For that, HSL comes as it helps us in defining a color according to its hue, saturation, and lightness, so now the forestgreen #228B22 and converting it to HSL will give the output as:
hsl(0, 100%, 50%)
Now, we can use this hsl(120, 61%, 34%) value to create “forestgreen” color and store it in one variable as shown below.
--color-forestgreen: hsl(120, 61%, 34%);
So, now let’s change the light or dark color. To do that, split the color values, and use the HSL function to build it again as shown below.
--color-forestgreen-h: 120; --color-forestgreen-s: 61%; --color-forestgreen-l: 34%; /* using hsl create the default forestgreen*/ --color-forestgreen: hsl(var(--color-forestgreen-h), var(--color-forestgreen-s), var(--color-forestgreen-l));
Our HSL is done and we got the default red color.
Using calc() function for darkening and light:
Now use the colors and override to using the forestgreen color versions.
Let us see an example to see how all of the above code CSS works in an HTML code.
Example: Below example demonstrates how to darken and lighten based on our “forestgreen” company color without any preprocessor in CSS. Hover over the box container and see how the “forestgreen” color of different shades changes into dark colors from lighter.
Please Login to comment...