Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring alternating divs of certain class

My code is as follows:

HTML

<div class="divs">
  <div class="row">row 0</div>
  <div class="not-row"></div>
  <div class="row">row 1</div>
  <div class="not-row"></div>
  <div class="row">row 2</div>
  <div class="not-row"></div>
  <div class="row">row 3</div> 
  <div class="not-row"></div>
</div>

CSS

.row:nth-child(even) {
  background: #fff;
}

.row:nth-child(odd) {
  background: #eee;
}

This is supposed to paint the background of two of the rows gray and two of the rows white. Unfortunately it paints all of their backgrounds gray. What am I doing wrong?

I tried using nth-of-type instead of nth-child but that didn't change anything.

jsFiddle example

like image 701
Benjy Kessler Avatar asked Feb 10 '23 11:02

Benjy Kessler


1 Answers

For even just use (as a default)

.row {}

Then override the odd ones with:

.row:nth-child(4n+1) {}

.row {
    background: #fff;
}
.row:nth-child(4n+1) {
   background: #eee;
}

http://jsfiddle.net/b8ma1hon/3/


More on how nth-child works can be found here:

https://css-tricks.com/how-nth-child-works/

enter image description here


You cannot simply use even/odd in this instance as that is in relation to all child elements, not just the ones with the class row.

Your inclusion of .row in the selector is purely an extra criteria and has no impact on the nth-child selector.

Likewise I could state:

.row:nth-child(1):hover {}

This would restrict selection to an element with a class of row, which is the 2nd child, which is currently in a hovered state.

It wouldn't make sense if this was the 2nd element out of all the hovered elements as you can only hover over one at a time.

I hope that makes sense!


It's also worth noting that your selector is now dependant on the not-row existing, or at least some kind of element existing between the row elements.

If this was to change then your selector would also have to change.

Alternatively you could change your element type for the not-row elements to something else so that you can make use of the nth-of-type selector:

<div class="divs">
    <div class="row">row 0</div>
    <span class="not-row"></span>
    <div class="row">row 1</div>
    <span class="not-row"></span>
    <div class="row">row 2</div>
    <span class="not-row"></span>
    <div class="row">row 3</div> 
    <span class="not-row"></span>
</div>

.row {
    background: #fff;
}
.row:nth-of-type(odd) {
   background: #eee;
}

http://jsfiddle.net/b8ma1hon/5/

like image 97
Curtis Avatar answered Feb 11 '23 23:02

Curtis