Zebra-like css style for nested divs

I have nested DIV elements for which I do not know the nesting levels. I need everyone to have a different background than their parent creating zebra-like colors. I use only two backgrounds - dark and white. The effect should be similar to the style of the odd and even children in the container, but in my case the children are nested. I can do this with the rules for each nested element, for example:

div div div div { background-color: #fff; } div div div { background-color: #aaa; } div div { background-color: #fff; } div { background-color: #aaa; } 

But I'm looking for a more elegant solution. Can this be done only with CSS? Do I need javascript?

Any suggestions would be highly appreciated.

Edit: I am looking for a solution that does not require the elements to have a class, since they must be rearranged using drag and drop (javascript)

+3
source share
1 answer

UPDATE: this solution is no longer relevant, given the update of the question. Leave it here for reference.

I would just use the β€œeven” and β€œodd” classes (or something similar):

 div.even { background-color: #fff; } div.odd { background-color: #aaa; } 

And then in the HTML:

 <div class="even"> <div class="odd"> <div class="even"> <div class="odd"> ... </div> </div> </div> </div> 
+1
source

Source: https://habr.com/ru/post/1240484/


All Articles