这个问题在这里已有答案:
我正在尝试实现一个非常具体的网格来展示一些项目。我们的想法是创建一个重复循环,其中第1,第2,第3,第4和第5项具有不同的样式(之后样式重复)。
例如:第一个红色背景/第二个蓝色背景/第三个绿色背景/第四个黄色背景/第五个黑色背景,它循环为项目数量(可能是5或28)。你会因此:#1红/#2蓝/#3绿/#4黄/#5黑/#6红/#7蓝/#8绿/#9黄等
我想使用纯CSS来创建这个循环。我使用webflow,因此内容在列表中逐个填充,我需要根据列表中的位置调整基本样式。
到目前为止我尝试使用的是nth-child:
.collection-list:nth-child(2n) .collection-item {}
.collection-list:nth-child(3n) .collection-item {}
.collection-list:nth-child(4n) .collection-item {}
.collection-list:nth-child(5n) .collection-item {}
它适用于5个第一项......但是......我的问题是,它似乎并不像循环一样......而且我认为这是因为2n和3n有时会发生冲突(例如当你有2 * 3时)。而且我不能使用奇数甚至是nth-child,因为我的想法是让它仅在5个项目之后循环...
有人有天才的想法吗?是否可以通过使用CSS?
谢谢!
问题是你如何定义公式。第n个子选择器中的公式如下:
nth-child(an+b)
其中a是循环的大小(在您的情况下为5),b是偏移值(或模数)。
这是一个工作片段:
.collection-list:nth-child(5n+0) .collection-item {background-color: red;}
.collection-list:nth-child(5n+1) .collection-item {background-color: blue;}
.collection-list:nth-child(5n+2) .collection-item {background-color: green;}
.collection-list:nth-child(5n+3) .collection-item {background-color: yellow;}
.collection-list:nth-child(5n+4) .collection-item {background-color: purple;}
<div class="collection-list"><div class="collection-item">1</div></div>
<div class="collection-list"><div class="collection-item">2</div></div>
<div class="collection-list"><div class="collection-item">3</div></div>
<div class="collection-list"><div class="collection-item">4</div></div>
<div class="collection-list"><div class="collection-item">5</div></div>
<div class="collection-list"><div class="collection-item">6</div></div>
<div class="collection-list"><div class="collection-item">7</div></div>
<div class="collection-list"><div class="collection-item">8</div></div>
<div class="collection-list"><div class="collection-item">9</div></div>
<div class="collection-list"><div class="collection-item">10</div></div>
真的简短回答:
2n
,3n
,4n
,...5n
,5n+1
,5n+2
,...如果你想要一个基于5的重复模式,你需要从5n
开始,然后减去或加号来选择你想要设置的兄弟。
例:
body {
counter-reset: divs;
display: flex;
flex-wrap: wrap;
}
div:nth-child(1n) {
counter-increment: divs;
background: purple;
min-width: 20%;
box-shadow:inset 0 0 0 1px;
}
div:before {
content: counter(divs);
padding: 1em;
}
body :nth-child(5n - 3) {
background: yellow;
}
body :nth-child(5n - 2) {
background: pink;
}
body :nth-child(5n - 1) {
background: lime;
}
body :nth-child(5n) {
background: tomato;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>