My CSS/HTML 在这里:
p:nth-child(2) {
background: #ff0000;
}
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
结果是行<p>The first paragraph.</p>
显示红色
为什么?我认为它必须在第 <p>The second paragraph.</p>
行中显示红色.
nth-child() 选择特定元素,如果它是父元素的第 n个(在您的情况下是第 2 个)子元素。
在这里,您需要使用 nth-of-type(),如果它是其父类型中的第 n 个(在您的例子中为 2nd),它将选择元素类型(假设 p)
p:nth-of-type(2) {
background: red;
}
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
使用 :nth-of-type(2)
p:nth-of-type(2) {
background: red;
}
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
因为 :nth-child(n) 选择器匹配作为其父级的第 n 个子元素的每个元素,无论其类型如何。
提示: 查看 :nth-of-type() 选择器以选择其父级的第 n 个特定类型的子元素。
来源: http://www.w3schools.com/cssref/sel_nth-child.asp
对于这个结果使用:nth-of-type( 2 )
,h1
也是一个孩子。