DEV Community

Cover image for Generate Different Background color based on ul depth using css variable
Jitesh Dhamaniya
Jitesh Dhamaniya

Posted on

Generate Different Background color based on ul depth using css variable

So Recently i have come across a requirement where i had to create separate background-color based on ul deptt, i had html like this

Alt Text

To do so i used two CSS Magical things. For Background color when we use hsl to define a color we can control a color based on a number. like this


background-color: hsl(100, 100%, 50%);


HSL is literally stands for Hue, Saturation, Lightness, so does the parameters. So changing hue will change the color.

Now second part is to figuring out dynamic number. Thanks to CSS variables we can define variables in css now. but i don't wanted to define hue number in css rather wanted to do using depth number which we can then convert to hue number using another css magic function which is calc. let me show you what i mean.


html {
/* Define a variable /
--depth:0;
}
ul {
/
Define background color */
background-color:hsl(calc(100 + var(--depth, 1) * 40 ), 100%, 50%);
}


here calc returns 100 for --depth:0 and 140 for --depth:1.

Now css part is done, in html we will override --depth variable value based on ul depth.

so now html would look like this

Alt Text

thats it. You will see different background colours all done in css.

You can check working snippet here.
https://codepen.io/jiteshdhamaniya/pen/NWboMKZ

Let me know if anyone does have better solution. See you next time.

P.S. - was having hard time, formatting ul, li code here, hence did the images.

Top comments (0)