【问题标题】:Debugging nth-child selector调试第 n 个子选择器
【发布时间】:2010-03-24 07:00:55
【问题描述】:

我有以下选择器:

.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 个开始) 等

我在 Ubuntu 上测试了 Firefox 3.5.8 和 Opera 10.10。也只在 CSS 中使用这些规则进行了测试。我正在使用 YUI 重置样式表,但排除它没有任何作用。

【问题讨论】:

  • 你能发布你定位的 HTML 吗?

标签: css css-selectors


【解决方案1】:

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

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

也许你误解了:nth-child的意思,你的HTML/CSS组合不正确。

foo:nth-child 不是指“foo 的第 n 个子元素的每个元素”,而是“每个 nth foo 元素”。

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

【讨论】:

【解决方案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 类移动到 &lt;div&gt; 然后使用这个 CSS:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多