CSS Zebra Nested Lists

It's easy to style lists and rows with alternating backgrounds using pseudo-classes :nth-child(odd/even), but if you try to apply it to nested lists, it will look disgusting.

My question is: is there a way to alternate in depth / hierarchy where, for example, the parent color alternates indefinitely with children. For instance:

  • red
    • blue
    • blue
      • red
      • red
        • blue
      • red
    • blue

jsfiddle

+2
source share
2 answers

The short answer is no. Long answer, yes, by targeting nested elements, for example:

li:nth-child(odd) {background:blue}
li:nth-child(odd) li:nth-child(even) {background:blue}
li:nth-child(even) li:nth-child(odd) {background:blue}

But for levels 2 or 3, you probably need a lot of rules.

You can do this with javascript as well, going through the tree and increasing the counter, applying a style when the counter is odd or even.

+5

All Articles