Nth-child every eight (8)
I need to repeat the pattern every eight such elements using nth-child.
■ □ ■ □
□ ■ □ ■
I'm trying to find a formula for this, but I don't seem to get it.
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>
+3
source to share
2 answers
If you need to keep an element <br>
, you don't want to use nth-child
it as it <br>
will be considered a child. You can use instead 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 seems like the best 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>
+4
source to share
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>
+1
source to share