我们有一系列的项目,这些项目排成一行,排在两列display: grid中.

我们还有5种牌子的 colored颜色 :橙色、蓝色、黄色、绿色、粉色.

行的背景 colored颜色 应按顺序在这些 colored颜色 上迭代,例如:

  • 第1行:橙色
  • 第2行:蓝色
  • 第3行:黄色
  • 第4行:绿色
  • 第5行:粉色
  • 第6行:(返回到5种 colored颜色 中的第一种)橙色
  • 第7行:蓝色
  • ...等等.

我知道如何使用:nth-child(5n + 1)遍历每个one项,如下面的代码片段所示.如果我们有<table>,其中每一对物品都包含在<tr>中,那么这种方法就可以很好地工作.

但在本例中,项没有分组,我们希望每two个项迭代一次.如何实现逐行上色的效果?

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;
}
<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>

推荐答案

一种解决方案是使用10n而不是5n,因此前两个元素将是li:nth-child(10n + 1), li:nth-child(10n + 2)

ul {
  display: grid;
  grid-auto-rows: 50px;
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

li:nth-child(10n + 1),
li:nth-child(10n + 2) {
  background: orange;
}

li:nth-child(10n + 3),
li:nth-child(10n + 4) {
  background: blue;
}

li:nth-child(10n + 5),
li:nth-child(10n + 6) {
  background: yellow;
}

li:nth-child(10n + 7),
li:nth-child(10n + 8) {
  background: green;
}

li:nth-child(10n + 9),
li:nth-child(10n) {
  background: pink;
}
<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>

Html相关问答推荐

从网络抓取中提取文本

如何防止下拉菜单内的Bootstrap列表行包装?

如何通过将项目包裹在迪夫中来保持最右列的对齐方式来对齐项目?

删除第一个列表项上的左边框

如何使用bslb设置可导航页面侧边栏的样式

Angular 滑块问题

在Hero部分中同时zoom 背景图像和形状的问题

有没有一种方法可以很容易地将这个div从底部:0转换到顶部:0?

使用bash从html表格中提取表格

Flex:第一个 div 有列,下一个 div 有行

如何在r中提取明显非标准html标签的值

如何在悬停时使用 CSS 更改许多同级元素

无法在 CSS 中将 h1 标签居中

在Firefox中使用keySplines时,SVG: <animateMotion>不起作用

CSS Grid 布局:1 大图和 3 小图

Tailwind:父母动态适应子元素的身高

如何垂直平移一个元素,使其新位置位于另外两个元素之间?

如何为某些行具有 rowspan 的表的每个奇数行着色

为什么相同持续时间的转换需要不同的时间?

如何阻止网格项目拉伸?