Adam Soffer
Adam Soffer

Reputation: 1664

Using nth-child to select an even, and then an odd number of elements

I'm attempting to style list items in this particular order:

1: White
2: White
3: Blue
4: Blue
5: Blue
6: White
7: White
8: Blue
9: Blue
10: Blue
11: White
12: White

The pattern is [1-2] [3-4-5] [6-7] [8-9-10]

My html structure is just a simple list:

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>    

Is this pattern possible using css nth-child? If so what would my selector look like?

Upvotes: 23

Views: 3071

Answers (4)

Rounin
Rounin

Reputation: 29463

Try:

ul li:nth-child(5n),
ul li:nth-child(5n-1),
ul li:nth-child(5n-2) {
color:rgb(0,0,255);
}

ul li:nth-child(5n-3),
ul li:nth-child(5n-4) {
color:rgb(255,255,255);
}

Upvotes: 25

web-tiki
web-tiki

Reputation: 103780

A shorter code for the same output would be :

li {
  color: white;
}
li:nth-child(5n-3),
li:nth-child(5n-4) {
  color: blue;
}

li {
  color: white;
}
li:nth-child(5n-4),
li:nth-child(5n-3) {
  color: blue;
}
/** FOR THE DEMO **/

body {
  background: grey;
}
<ul>
  <li>1. text</li>
  <li>2. text</li>
  <li>3. text</li>
  <li>4. text</li>
  <li>5. text</li>
  <li>6. text</li>
  <li>7. text</li>
  <li>8. text</li>
  <li>9. text</li>
  <li>10. text</li>
  <li>11. text</li>
  <li>12. text</li>
</ul>

The point is that you don't need to specify which element the white color should apply to but just the ones that need to be Blue as it will override the "default" set white color.

Upvotes: 16

Salman Arshad
Salman Arshad

Reputation: 272106

[Thinking aloud]

  • Every 5th item starting from 1 is white
  • Every 5th item starting from 2 is white
  • Every 5th item starting from 3 is blue
  • Every 5th item starting from 4 is blue
  • Every 5th item starting from 5 is blue

In order to translate this repeating pattern into :nth-child(an+b), we need five selectors:

  • a will be 5
  • b will be from 1 to 5

And the result:

li:nth-child(5n+1),
li:nth-child(5n+2) {
  background-color: #FFF;
}
li:nth-child(5n+3),
li:nth-child(5n+4),
li:nth-child(5n+5) {
  background-color: #00F;
}
<ul>
  <li>1: White</li>
  <li>2: White</li>
  <li>3: Blue</li>
  <li>4: Blue</li>
  <li>5: Blue</li>
  <li>6: White</li>
  <li>7: White</li>
  <li>8: Blue</li>
  <li>9: Blue</li>
  <li>10: Blue</li>
  <li>11: White</li>
  <li>12: White</li>
</ul>

Upvotes: 5

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

Try like so:

li:nth-child(5n - 4),
li:nth-child(5n - 3)  {
    color: white;
}

li:nth-child(5n - 2),
li:nth-child(5n - 1),
li:nth-child(5n)  {
    color: blue;
}

Live Example: http://codepen.io/anon/pen/vENgbx

Upvotes: 9

Related Questions