如何实现任意层级嵌套列表项目符号按绿-蓝-灰规则循环配色
实现方案
你可以通过以下两种方式实现任意层级的循环配色需求:
方案1:高兼容性实现(推荐)
绝大多数场景下嵌套列表不会超过10层,我们只需要提前写好10层的匹配规则即可覆盖全部使用场景,同时兼容所有主流浏览器:
首先抽离公共样式避免冗余,再按3层一循环的规则匹配颜色:
/* 公共样式 */ ul { margin-bottom: 20px !important; font-weight: 800; list-style: none; } li::before { content: "\25CF "; display: inline-block; width: 1em; margin-left: -1em; font-size: 18px; } /* 第1、4、7、10层 → 绿色 */ li::before, ul ul ul li::before, ul ul ul ul ul ul li::before, ul ul ul ul ul ul ul ul ul li::before { color: green; } /* 第2、5、8、11层 → 蓝色 */ ul li::before, ul ul ul ul li::before, ul ul ul ul ul ul ul li::before, ul ul ul ul ul ul ul ul ul ul li::before { color: blue; } /* 第3、6、9、12层 → 灰色 */ ul ul li::before, ul ul ul ul ul li::before, ul ul ul ul ul ul ul ul li::before, ul ul ul ul ul ul ul ul ul ul ul li::before { color: gray; }
如果需要支持更深层级,只需要按照规律在对应分组补加ul的数量即可。
方案2:现代CSS无限层级实现
如果不需要兼容旧版浏览器,可以用CSS自定义属性+条件规则实现真正的无限层级适配,不需要手动补加规则:
@property --depth { syntax: '<number>'; inherits: true; initial-value: 0; } /* 公共样式 */ ul { --depth: calc(var(--depth) + 1); margin-bottom: 20px !important; font-weight: 800; list-style: none; } li::before { content: "\25CF "; display: inline-block; width: 1em; margin-left: -1em; font-size: 18px; --level: calc(var(--depth) % 3); } @when var(--level) = 1 { li::before { color: green; } } @when var(--level) = 2 { li::before { color: blue; } } @when var(--level) = 0 { li::before { color: gray; } }
内容的提问来源于stack exchange,提问作者pepe199111
相关产品推荐
相关产品推荐

