开发者

Debugging nth-child selector

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 the开发者_开发技巧se rules in the CSS. I'm using the YUI Reset stylesheet but excluding it does nothing.


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 nth child of foo’ but ‘every nth foo element’.

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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜