Search code examples
csspseudo-class

Zebra-striping nested lists with CSS


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

My question is, is there any way to alternate by depth / hierarchy, where, for example, a parent color alternates with the child elements' indefinitely. Eg:

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

jsfiddle


Solution

  • Short answer, no. Long answer, yes, by targeting the nested items, eg:

    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 beyond 2 or three levels you're probably going to need a lot of rules.

    You could do it with javascript as well, by walking down the tree and incrementing a counter, applying the style when the counter is odd or even.