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