Search code examples
htmlcsscss-selectorshtml-listspseudo-class

Grouped sequence with CSS :nth-child


ul,li {
  display: block;
  margin:0;
  padding:0;
  list-style:none;
}
li {
  background: black;
  color: white;
  padding: 10px;
}
li:nth-child(2n+2) {
  background: red;
}
li:nth-child(3n+3) {
  background: green;
}
li:nth-child(4n+4) {
  background: blue;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
  <li>nine</li>
  <li>ten</li>
  <li>eleven</li>
  <li>twelve</li>
</ul>

What I need:

  1. black
  2. red
  3. green
  4. blue
  5. black
  6. red
  7. green
  8. blue
  9. ...

... how do I achieve this with :nth-child?


Solution

  • given the nth-child syntax

    :nth-child( <an-plus-b>  )
    

    you need to iterate using 4n+b

    So,

    for background red it will be 4n+2 so, 4x0+2, 4x1+2, 4x2+2 and so on, which gives you elements 2, 6, 10

    for background green it will be 4n+3 so, 4x0+3, 4x1+3, 4x2+3 and so on, which gives you elements 3, 7, 11

    and for background'blue, it will be 4n+4 so, 4x0+4, 4x1+4, 4x2+4 and so on, which gives you elements 4, 8, 12

    The remaining elements 1, 5, 9 will be colored black by default given your property in li

    ul,li {
      display: block;
      margin:0;
      padding:0;
      list-style:none;
    }
    li {
      background: black;
      color: white;
      padding: 10px;
    }
    li:nth-child(4n+2) {
      background: red;
    }
    li:nth-child(4n+3) {
      background: green;
    }
    li:nth-child(4n+4) {
      background: blue;
    }
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
      <li>four</li>
      <li>five</li>
      <li>six</li>
      <li>seven</li>
      <li>eight</li>
      <li>nine</li>
      <li>ten</li>
      <li>eleven</li>
      <li>twelve</li>
    </ul>