调试nth-child选择器

时间:2010-03-23 21:05:06

标签: css css-selectors

我有以下选择器:

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

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

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

然而,所有物品都以青色背景结束。这些选择器是否正确?我想我应该得到:

  1. 青色(每3个,从1开始)
  2. 红色(每3个,从2开始)
  3. 蓝色(每3个,从3开始) 等
  4. 我在Ubuntu上测试了Firefox 3.5.8和Opera 10.10。还在CSS中测试了除了这些规则之外的任何内容。我正在使用YUI重置样式表,但排除它什么都不做。

2 个答案:

答案 0 :(得分:4)

您的CSS似乎是正确的,假设以下HTML:

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

也许您误解了:nth-child的含义,并且您的HTML / CSS组合不正确。

foo:nth-child并不意味着“foo”的所有 n 孩子的元素,而是“每个 n th {{ 1}}元素'。

专业提示:使用the :nth-child() tester。或者这个:http://leaverou.me/demos/nth.html

答案 1 :(得分:2)

我猜测.progress的每次出现实际上都是元素的第一个孩子。为了使您的示例正常工作,所有.progress元素必须是兄弟姐妹。

即。这将有效:

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

......但这不会:

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

在这种情况下,您需要将progress类移至<div>,然后使用此CSS:

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