Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select nth-child(n) except the first matching child

I want to select all elements matching nth-child(2n) in a list except for the first matching element; for example…

li:nth-child(2n) {
  background: red;
}

li:nth-child(2) {
  background: none;
}
<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>
</ul>

The result of this is that only Four, Six, Eight and Ten have a red background color.

I would like to know if there’s a better way of expressing the CSS rules though, and if it’s possible to express as a single rule:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

li:nth-child(2n) {
    background: red;
}

li:nth-child(2) {
    background: none;
}

Can these be combined and still behave the same way?

>Solution :

You can use a :not() pseudo-class to exclude the second nth child.

li:nth-child(2n):not(:nth-child(2)) {
  background: red;
}

A better way would be to use the An+B syntax for :nth-child() to select every second child starting with the fourth child.

li:nth-child(2n+4) {
  background: red;
}
<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>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading