:h1和p的n-child奇怪行为

Dor*_*ian 1 html css css-selectors css3

p:nth-child(1)在以下代码中使用时,第一段不会被选中:

p:nth-child(1) {
  background:#ff0000;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Unrelated</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
Run Code Online (Sandbox Code Playgroud)

检查这个jsBin

但是当删除h1它有效时,请参阅此jsBin

知道为什么吗?

Tyl*_*erH 13

p:nth-child(1)选择的p元素也是父元素第一个子元素(在本例中body).p在这种情况下,没有元素也是父元素的第一个子元素; 这里父元素的第一个子元素是h1.你想要的是,p:nth-of-type(1)或者更直接地p:first-of-type.