Olivier Pons
Olivier Pons

Reputation: 15778

Css: :nth-child: what am I missing?

I have 2 div which are like 2 td's in a table. Thus I want 2 divs red, then 2 divs blue and so on. This doesn't, work, what am I missing:

<style>
.irow :nth-child(4n+0), .irow :nth-child(4n+1) {
  background-color: blue;
}
.irow :nth-child(4n+2), .irow :nth-child(4n+3) {
  background-color: red;
}
</style>

<div class="irow">
    <div class="col-md-8">Inès va morfler grave</div>
    <div class="col-md-4">Tête</div>
    <div class="col-md-8">Inès que des mots&nbsp;!</div>
    <div class="col-md-4">Pompon</div>
</div>

Upvotes: 0

Views: 213

Answers (2)

Kaspar Lee
Kaspar Lee

Reputation: 5596

You need to use the following CSS:

.irow div:nth-child(4n+1), .irow div:nth-child(4n+2){
  background-color: red;
}
.irow div:nth-child(4n+3), .irow div:nth-child(4n+4) {
  background-color: blue;
}

This is how it works:

xn selects every xth element, and the +number is the offset. For example 2n+1 will find every element this is a multiple of 2, and select the one after it (+1). This would return the the element with the following indexes: `3, 5, 7, 9'.

In the code I posted above, the first rule selects every 4th element (i.e. the 4th, the 8th). The second one selects every 4th element +1 (i.e. the 5th, the 9th), and so on for the other two

JSFiddle

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

Try this https://jsfiddle.net/2Lzo9vfc/257/

.irow div:nth-child(4n+1),
.irow div:nth-child(4n+2) {
  background-color: blue;
}
.irow div:nth-child(4n+3),
.irow div:nth-child(4n+4){
  background-color: red;
}

Upvotes: 1

Related Questions