Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate color every 4 items [duplicate]

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...

like image 227
Simon Avatar asked Jan 26 '23 09:01

Simon


2 Answers

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>
like image 60
Jason Aller Avatar answered Feb 03 '23 15:02

Jason Aller


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>
like image 38
kukkuz Avatar answered Feb 03 '23 17:02

kukkuz