我需要使用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>
答案 0 :(得分:4)
如果您必须保留<br>
元素,那么您不想使用nth-child
,因为<br>
将被视为孩子。相反,您可以使用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;
}
&#13;
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
&#13;
根据您问题中的更新信息,看起来更好的解决方案是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;
}
&#13;
<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>
&#13;
答案 1 :(得分:1)
div:nth-child(8n + 1) { background-color: green; }
div:nth-child(8n + 2) { background-color: orange; }
div:nth-child(8n + 3) { background-color: aqua; }
div:nth-child(8n + 4) { background-color: red; }
div {
width: 50px;
height: 50px;
display: inline-block;
background-color: yellow;
}
section {
width: 220px;
}
<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>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>