You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS实现交替行背景色 重复元素组颜色统一且不影响后续元素

解决方案

可以通过CSS原生选择器实现,完全满足所有约束条件,代码如下:

/* 基础交替配色规则 */
section {
  background-color: blue;
}
section:nth-of-type(even) {
  background-color: red;
}

/* 统一dupe组的颜色:首个dupe保留原奇偶配色,后续dupe继承首个dupe的颜色 */
.dupe:first-of-type {
  background-color: revert-layer;
}
.dupe ~ .dupe {
  background-color: inherit;
}

/* 修正dupe组之后的普通section的交替逻辑:
如果dupe总数量为偶数,说明dupe组比单个元素多占了奇数个位置,翻转后续所有非dupe元素的配色 */
body:has(.dupe:nth-of-type(even of .dupe):last-of-type) .dupe ~ section:not(.dupe):nth-of-type(odd) {
  background-color: red;
}
body:has(.dupe:nth-of-type(even of .dupe):last-of-type) .dupe ~ section:not(.dupe):nth-of-type(even) {
  background-color: blue;
}

实现说明

  1. 先基于原生nth-of-type给所有section设置默认的交替背景
  2. 首个带dupe类的section保留默认计算出的背景色,后续所有同组dupe直接继承前面的颜色,保证整组颜色统一
  3. 通过:has()判断dupe组的总长度:如果dupe总数是偶数,说明dupe组比单个元素多占用了奇数个DOM位置,直接翻转后续所有普通section的配色,即可保证后续交替逻辑和原有规则完全一致
  4. 兼容dupe组在任意位置、任意长度的场景,无需修改DOM结构

兼容性说明:该方案用到的语法在Chrome 105+、Firefox 121+、Safari 15.4+均已支持,覆盖95%以上主流用户。


内容的提问来源于stack exchange,提问作者Khang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:09:01