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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay