views:

164

answers:

2

I have the following selectors:

.progress:nth-child(3n+1) {
    background: teal;
}

.progress:nth-child(3n+2) {
    background: red;
}

.progress:nth-child(3n+3) {
    background: blue;
}

However all of the items end up with a teal background. Are these selectors correct? I'm thinking I should get:

  1. Teal (every 3, starting with 1)
  2. Red (every 3, starting with 2)
  3. Blue (every 3, starting with 3) etc.

I've tested on Firefox 3.5.8 and Opera 10.10 on Ubuntu. Also tested with nothing but these rules in the CSS. I'm using the YUI Reset stylesheet but excluding it does nothing.

+3  A: 

Your CSS seems to be correct, assuming the following HTML:

<div class="progress">1</div>
<div class="progress">2</div>
<div class="progress">3</div>

Perhaps you misunderstood the meaning of :nth-child, and your combination of HTML/CSS is incorrect.

foo:nth-child doesn't mean ‘every element that is the the *n*th child of foo’ but ‘every *n*th foo element’.

Pro tip: use the :nth-child() tester. Or this one: http://leaverou.me/demos/nth.html

Mathias Bynens
Well they work on there, any ideas why not in my page?
Ross
Post your html.
Catfish
@Ross: Like I said, there’s probably something wrong with your HTML. Here’s a working demo of the above example: http://jsfiddle.net/mathias/cKr67/
Mathias Bynens
Ah yeah my html is wrong, they're inside table cells.
Ross
+2  A: 

I'm guessing that each occurrence of .progress is actually the first child of an element. For your example to work, all .progress elements must be siblings.

i.e. this will work:

<div class="progress">1</div>
<div class="progress">2</div>
<div class="progress">3</div>

...but this won't:

<div><span class="progress">1</span></div>
<div><span class="progress">2</span></div>
<div><span class="progress">3</span></div>

In this case you'd need to move the progress class to the <div> then use this CSS:

.progress:nth-child(3n+1) span {
    background: teal;
}
DisgruntledGoat