Mike Young
Mike Young

Reputation: 321

nth-child pattern starting after a particular child

How can you do an nth-child pattern like below:

div:nth-child(3n+1){
   background: #FF7100;
}
div:nth-child(3n+2){
   background: #FFB173;
}
div:nth-child(3n+3){
   background: #A64A00;
}

but to skip for instance the first child and only start this pattern after the first child. I tried chaining it like below but it did not seem to work:

 div:nth-child(n+1):nth-child(3n+1) {
    background: #FF7100;
}

Upvotes: 2

Views: 47

Answers (2)

Pugazh
Pugazh

Reputation: 9561

Use :not(:first-child) selector to skip the first-child.

div:not(:first-child):nth-child(3n+1) {
  background: #FF7100;
}
div:nth-child(3n+2) {
  background: #FFB173;
}
div:nth-child(3n+3) {
  background: #A64A00;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>

If you wanna skip first element for each style, try this

div:nth-child(1) ~ div:nth-child(3n+1) {
  background: #FF7100;
}
div:nth-child(2) ~ div:nth-child(3n+2) {
  background: #FFB173;
}
div:nth-child(3) ~ div:nth-child(3n+3) {
  background: #A64A00;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>

Upvotes: 4

Colby Sargent
Colby Sargent

Reputation: 341

Pugazh's answer is the better answer, but just to explain why your initial attempt didn't work (I'm brand new, not enough rep to comment instead)

in CSS selectors, n starts at 0, so nth-child(n+1) was still selecting the 1st (0+1)th element, so nth-child(n+2) would've worked using your method

Upvotes: 1

Related Questions