使用CSS的斑马纹嵌套列表 [英] Zebra-striping nested lists with CSS

查看:352
本文介绍了使用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

      • 红色

      • 红色

        • 蓝色

        jsfiddle

        推荐答案

        简短的答案,没有。答案是肯定的,通过定位嵌套项,例如:

        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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆