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