Home > OS >  Select nth-child(n) except the first matching child
Select nth-child(n) except the first matching child

Time:11-02

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?

CodePudding user response:

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>

CodePudding user response:

Sure, use li:nth-child(2n 4). The format of the nth-child selector is An B, where:

  • A is an integer step size,
  • B is an integer offset,
  • n is all nonnegative integers, starting from 0.

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>

In the format (2n 4), you're essentially starting from the fourth element (1 based index) and incrementing by two each time. So, 4, 6, 8, ...

CodePudding user response:

CSS :nth-child Selectors -> You will find the answer below the README.

NOTE: Remember to scroll down to the bottom.

css-nth-child-selectors codes -> There is also a view of the entire file, separated by header.

I hope it will be useful for you.

The most appropriate for this situation would be the following:

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