html - 未应用 HTML5 "article"标记上的第一个子项和第 n 个子项选择器

标签 html css css-selectors

我在 HTML5 上使用一些 CSS2 和 CSS3 选择器 <article>标签,但似乎有一些(但不是全部)没有像我预期的那样工作。

这是一个可运行的例子:

/* Working as expected: */
div.wrapper p:first-child { color: red; }
div.wrapper p:nth-child(even) { color: fuchsia; }

/* NOT working as expected: */
div.wrapper article:nth-child(1) { color: blue; }
div.wrapper article:first-child { color: green; }

/* Working as expected: */
div.wrapper article:last-child { color: gold; }
<div class="wrapper">
  <p>P1, expected "color: red"</p>
  <p>P2, expected "color: fuchsia"</p>
  <p>P3, expected no css applied</p>
  <p>P4, expected "color: fuchsia"</p>
  <article>Article 1, expected "color: green" and/or "color: blue" &larr; not working as expected...</article>
  <article>Article 2, expected "color: gold"</article>
</div>

然后我的问题是:为什么 nth-child(n) 不会和 first-child <article> 上的选择器标签有用吗?甚至更奇怪:last-child选择器确实有效。我在 FF4、IE9 和 Chrome11 中测试,结果都是一样的。

<p>标签起到健全性检查的作用;看到nth-child(n)选择器确实适用于某些标签。

我错过了什么?我的样本是否应该有效?

最佳答案

first-child仅当标签是其父标签的第一个子标签时才选择该标签。在您的情况下,第一个 <article> tag 是第五个标签。 同样适用于 nth-child(n) .它与同一类型的兄弟标签无关,而是与所有兄弟标签相关。来自 W3C:

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

来源:http://www.w3.org/TR/css3-selectors/#nth-child-pseudo

关于html - 未应用 HTML5 "article"标记上的第一个子项和第 n 个子项选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256372/

相关文章:

javascript - 我想使用 javascript 将不同的 url 链接分配给激活单选按钮时生成的按钮

html - 样式表 CSS 和 HTML

css - 像 cssdeck 这样的编播功能

html - 悬停在一个 div 上并显示另一个 div

html - 如何在数据(pdf)从 URL 加载到 HTML 对象元素中时显示微调器或进度

提交表单时 PHP $_POST 数组始终为空

html - 如何使 'dl' 内容自动换行,就像表 'td' 换行一样?

html - 对齐并行有序列表

html - CSS 优先规则未正确应用于输入框的宽度

CSS :first-child unexpectedly working fine