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

能否用CSS实现元素背景色按指定颜色组重复循环?

实现多个元素背景色循环的CSS方案

完全可以做到!不用一个个手动给每个.item写样式,CSS里的:nth-child()选择器有个超实用的公式语法,刚好能搞定这种按指定颜色组循环的需求。

核心思路

利用:nth-child(an + b)的公式匹配规则:

  • a是你想要的循环周期数(这里就是5种颜色,所以a=5)
  • b对应颜色组里的位置(从1到5,分别对应每一种颜色)

这样每第5n+1、5n+2...的元素会自动匹配对应颜色,不管你有20个还是更多元素,都会按5色组循环下去。

代码示例

/* 定义5种循环背景色 */
.item:nth-child(5n + 1) {
  background-color: #ff4444; /* 红色 */
}
.item:nth-child(5n + 2) {
  background-color: #ffbb33; /* 黄色 */
}
.item:nth-child(5n + 3) {
  background-color: #00C851; /* 绿色 */
}
.item:nth-child(5n + 4) {
  background-color: #33b5e5; /* 蓝色 */
}
.item:nth-child(5n + 5) {
  background-color: #aa66cc; /* 紫色 */
}

原理说明

  • 5n + 1会匹配第1、6、11、16...个元素(n从0开始计数:05+1=1,15+1=6,以此类推)
  • 5n + 2匹配第2、7、12、17...个元素,以此类推,刚好实现每5个元素一轮颜色循环

如果之后要调整颜色数量,只需要修改a的值(比如改成3就是3种颜色循环),再对应增减nth-child的规则就行,非常灵活。

另外,如果你的.item元素不是直接的兄弟节点(比如嵌套在其他容器里),可以改用:nth-of-type()选择器,效果完全一致,只需要把.item:nth-child()换成.item:nth-of-type()就好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:17:33