Home > other >  Exclude children from :nth-child(n) / only include certain children
Exclude children from :nth-child(n) / only include certain children

Time:07-17

Is it possible to only select certain children? Say, the 2nd, 3rd, 5th and 7th?/exclude the 1st and 6th?

This selects all div, and I know e.g n 2 starts at 2 onwards and 2 is only the 2nd.

div:nth-child(n){

}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>

CodePudding user response:

It may be clearer to exclude certain children rather than find a selector for all those to be included. This depends on the exact use case of course.

For the example in the question this snippet specifies two children which are to be excluded using a :not pseudo class:

div:not(:nth-child(1), :nth-child(6)) {
  color: red;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>

CodePudding user response:

Yes you can use :nth-child combined,

where: div:nth-child(2) is for the 2nd element, and div:nth-child(2n 3) is for 3rd, 5th, 7th, with calculation being made in this way:

  • 2x0 3 = 3
  • 2x1 3 = 5
  • 2x2 3 = 7

div:nth-child(2),
div:nth-child(2n 3) {
  background: lightblue;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>

  • Related