如何使用CSS :nth-child按每组2个元素实现网格行背景色循环?
问题:两列Grid布局列表实现行背景色循环
我们有一系列采用两列display: grid布局的列表项,需要让网格行的背景色按orange、blue、yellow、green、pink这5种颜色循环,效果如下:
- 第1行:orange
- 第2行:blue
- 第3行:yellow
- 第4行:green
- 第5行:pink
- 第6行:orange(回到第一种颜色)
- 以此类推
之前在<table>里可以用:nth-child(5n + 1)这类选择器给每行(由<tr>包裹的两个元素)设置循环样式,但现在列表项没有分组,要按每组2个元素实现整行同色的循环效果,该怎么操作?
初始代码如下:
CSS
ul { display: grid; grid-auto-rows: 50px; grid-template-columns: repeat(2, minmax(0, 1fr)); } li:nth-child(5n + 1) { background: orange; } li:nth-child(5n + 2) { background: blue; } li:nth-child(5n + 3) { background: yellow; } li:nth-child(5n + 4) { background: green; } li:nth-child(5n + 5) { background: pink; }
HTML
<ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul>
解决方案
核心思路:因为每行包含2个列表项,5种颜色循环一轮需要覆盖5×2=10个元素,所以我们需要针对每一行的两个连续元素设置相同背景色,通过调整:nth-child的公式来匹配对应行的元素。
修改后的CSS代码:
ul { display: grid; grid-auto-rows: 50px; grid-template-columns: repeat(2, minmax(0, 1fr)); } /* 匹配第1、6、11...行的两个元素 */ li:nth-child(10n + 1), li:nth-child(10n + 2) { background: orange; } /* 匹配第2、7、12...行的两个元素 */ li:nth-child(10n + 3), li:nth-child(10n + 4) { background: blue; } /* 匹配第3、8、13...行的两个元素 */ li:nth-child(10n + 5), li:nth-child(10n + 6) { background: yellow; } /* 匹配第4、9、14...行的两个元素 */ li:nth-child(10n + 7), li:nth-child(10n + 8) { background: green; } /* 匹配第5、10、15...行的两个元素 */ li:nth-child(10n + 9), li:nth-child(10n + 10) { background: pink; }
说明
10n是循环周期,对应5种颜色×每行2个元素的总数量,每10个元素完成一次颜色循环。- 每个颜色对应的两个选择器,分别选中该行的第一个和第二个列表项,确保整行背景色一致。
- 保持HTML结构不变,仅通过CSS即可实现需求效果。
内容的提问来源于stack exchange,提问作者RobertAKARobin
相关产品推荐
相关产品推荐

