Is it possible with pure CSS to create a color grid that alternates every 4 items. Eg; First 4 items to have blue color, the next 4 to have red and then the next 4 back to blue and so on.
<div>Item 1 = blue</div>
<div>Item 2 = blue</div>
<div>Item 3 = blue</div>
<div>Item 4 = blue</div>
<div>Item 5 = red</div>
<div>Item 6 = red</div>
<div>Item 7 = red</div>
<div>Item 8 = red</div>
<div>Item 9 = blue</div>
Any ideas? I know there is nth-child(odd)
and even
but not sure that helps here...
Using a default rule for the red, and a rule that repeats with an offset for the blue it is possible.
The syntax of 8n+1
every 8 offset by 1, and then this is repeated to get 1 through 4.
div {
color: red;
}
div:nth-child(8n+1),
div:nth-child(8n+2),
div:nth-child(8n+3),
div:nth-child(8n+4) {
color: blue;
}
<div>Item 1 = blue</div>
<div>Item 2 = blue</div>
<div>Item 3 = blue</div>
<div>Item 4 = blue</div>
<div>Item 5 = red</div>
<div>Item 6 = red</div>
<div>Item 7 = red</div>
<div>Item 8 = red</div>
<div>Item 9 = blue</div>
You can use some verbose nth-child logic - see demo below:
div:nth-child(4n),
div:nth-child(4n - 1),
div:nth-child(4n - 2),
div:nth-child(4n - 3) {
color: blue;
}
div:nth-child(8n),
div:nth-child(8n - 1),
div:nth-child(8n - 2),
div:nth-child(8n - 3) {
color: red;
}
/* stylings */
body {
counter-reset: counter;
}
div {
counter-increment: counter;
}
div:after {
content: counter(counter);
}
<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><div></div><div></div><div></div><div></div><div></div><div></div>
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