Corentin Branquet
Corentin Branquet

Reputation: 1576

Select the three first divs

In CSS I want to select the three first divs. I have this code:

div:nth-child(3n) {
  background: red;
}
<div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore laborum necessitatibus nobis obcaecati, mollitia, eos sint dolor odit. Possimus dolores recusandae sed totam, voluptatibus, voluptatum. Voluptatibus minus aut, quam ratione.
</div>

<div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates perferendis et saepe omnis nemo, dolores quia ipsam ea blanditiis quaerat autem aut id itaque magnam recusandae sint architecto! Error, consequuntur.
</div>

<div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem doloremque quis perspiciatis vel odio impedit itaque laborum eveniet quasi aperiam, autem cumque vero recusandae, voluptates et nesciunt quibusdam aliquid! Deleniti.
</div>

<div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem doloremque quis perspiciatis vel odio impedit itaque laborum eveniet quasi aperiam, autem cumque vero recusandae, voluptates et nesciunt quibusdam aliquid! Deleniti.
</div>

I try above CSS but it does not work.

Upvotes: 6

Views: 531

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240928

It's not working as expected because :nth-child(3n) will select every third element.

You need to select every element starting from the third one counting backwards, therefore you could use -n + 3 or -1n + 3.

In other words, given the pattern an+b, a should be 1 (or omitted) since you don't want to skip over elements. In addition, a should also be negative and b should be 3 since you're starting at the third element.

div:nth-child(-1n + 3) {
  background: #f00;
}
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>

It's worth pointing out that div:nth-child(-1n + 3) will only select the element if it is one of the first three elements and also an element type div. In other words, if the third element is a span, only the first two div elements will be selected:

div:nth-child(-1n + 3) {
  background: red;
}
<div>First div</div>
<div>Second div</div>
<span>Span</span>
<div>Third div</div>

If the element types vary (like above), then you should use :nth-of-type() instead:

div:nth-of-type(-1n + 3) {
  background: red;
}
<div>First div</div>
<div>Second div</div>
<span>Span</span>
<div>Third div</div>

Upvotes: 11

Related Questions