使用CSS的斑马纹嵌套列表 [英] Zebra-striping nested lists with CSS
问题描述
使用:nth-child(odd / even)
伪类别,可以轻松地为具有交替背景的列表和行设置样式,但如果您尝试将其应用于嵌套列表,它开始看起来可怕。
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:
- 红
- 蓝
- blue
- 红色
- 红色
- 蓝色
推荐答案
简短的答案,没有。答案是肯定的,通过定位嵌套项,例如:
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}
但是超过2级或3级,你可能需要很多规则。
But beyond 2 or three levels you're probably going to need a lot of rules.
您也可以使用javascript来做,通过在树上走下来并增加计数器,当计数器是奇数或偶数时应用样式。
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.
这篇关于使用CSS的斑马纹嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!