Zebra-striping nested lists with CSS

旧街凉风 提交于 2019-12-22 20:02:43

问题


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


回答1:


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.




回答2:


BAM! http://jsfiddle.net/taEgL/



来源:https://stackoverflow.com/questions/9867471/zebra-striping-nested-lists-with-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!