I need to repeat a pattern every eight elements like this using nth-child.
■□■□
□■□■
I've been trying to figure out a formula for this but I don't seem to get it right.
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>
If you have to keep the <br> element then you don't want to use nth-child as the <br> will count as a child. Instead you can use nth-of-type:
div:nth-of-type(5n+1),div:nth-of-type(5n+3) {
background-color: green;
}
Example:
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>
Based on the updated information in your question it looks like the better solution is 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With