我的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>
中显示红色。
答案 0 :(得分:2)
nth-child()选择特定元素,如果它是父元素的第n个(在您的情况下是第2个)子元素。
在这里你需要使用nth-of-type()来选择元素类型(比方说p),如果它是父类型中的第n个(在你的情况下是第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>
答案 1 :(得分:1)
使用: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>
答案 2 :(得分:1)
因为:nth-child(n)选择器匹配其父元素的第n个子元素,无论其类型如何。
提示:查看:nth-of-type()选择器,选择其父元素的特定类型的第n个子元素。
答案 3 :(得分:0)
该结果使用:nth-of-type( 2 )
,h1
也是孩子。