我需要像这样使用第 nth-child 每八个元素重复一个模式。
■□■□
□■□■
我一直在试图找出一个公式,但我似乎没有弄对。
section {
width: 220px;
}
div {
width: 50px;
height: 50px;
float: left;
margin-right: 5px;
margin-bottom: 5px;
background-color: yellow;
}
div:nth-child(4n), div:nth-child(4n+1) {
background-color: green;
}
<section>
<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>
</section>
最佳答案
如果您必须保留 <br>
元素,那么你不想使用 nth-child
作为 <br>
会算作 child 。相反,您可以使用 nth-of-type
:
div:nth-of-type(5n+1),div:nth-of-type(5n+3) {
background-color: green;
}
例子:
div {
width: 50px;
height: 50px;
display: inline-block;
background-color: yellow;
}
div:nth-of-type(5n+1),div:nth-of-type(5n+3) {
background-color: green;
}
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
根据您问题中的更新信息,看起来更好的解决方案是 div:nth-of-type(8n+1), div:nth-of-type(8n+3),div:nth-of-type(8n+6), div:nth-of-type(8n+8) { background-color: green; }
body {
font-size: 10pt;
}
section {
width: 220px;
}
div {
width: 50px;
height: 50px;
float: left;
margin-right: 5px;
margin-bottom: 5px;
background-color: yellow;
}
div:nth-of-type(8n+1),
div:nth-of-type(8n+3),
div:nth-of-type(8n+6),
div:nth-of-type(8n+8) {
background-color: green;
}
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div>Should repeat here</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>Should repeat here</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>
</section>
关于html - 每八个 (8) 第 n 个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45037879/