user1469270
user1469270

Reputation:

Using nth child (for every 3 + 1)

I am trying to style a series of divs, depending on their position. I want them to be styled, like so:

<div class="col33"></div> <!--  red -->
<div class="col33"></div>
<div class="col33"></div> <!--  orange -->

<div class="col33"></div> <!--  red -->
<div class="col33"></div>
<div class="col33"></div> <!--  orange -->

<div class="col33"></div> <!--  red -->
<div class="col33"></div>
<div class="col33"></div> <!--  orange -->

But I can only seem to get every third child:

.col33:nth-child(3n) {
    background-color: orange;
}

http://jsfiddle.net/UAj6h/3/

Upvotes: 1

Views: 95

Answers (2)

chrona
chrona

Reputation: 1911

Just add .col33:nth-child(3n-2) or .col33:nth-child(3n+1) for your red divs.

.col33:nth-child(3n-2) {
    background: #ff4136;
}

DEMO

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Just add another rule for 3n+1 div

.col33:nth-child(3n) {
    background-color: orange;
}
.col33:nth-child(3n+1) {
   background-color: red;
}

Example fiddle: http://jsfiddle.net/UAj6h/4/

As a side note, you may avoid to use redundant .col33 class, in order to reduce markup size and you may target those div with .parent-div > div

Upvotes: 3

Related Questions