:第n个孩子奇怪的行为与h1和p [英] :nth-child strange behavior with h1 and p

查看:96
本文介绍了:第n个孩子奇怪的行为与h1和p的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using p:nth-child(1) in the following code, the first paragraph doesn't get selected:

p:nth-child(1) {
  background:#ff0000;
}





<h1>Unrelated</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

检查此 jsBin

但是当删除 h1 href =http://jsbin.com/xocuvomo/2/ =nofollow> jsBin

But when remove a h1 it works, see this jsBin

任何想法为什么?

推荐答案

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

p:nth-child(1) is selecting the p element that is also the first child of the parent element (in this case body). There are no p elements that are also the first child of the parent element in this case; the first child of the parent element here is h1. What you want is p:nth-of-type(1) or, more directly, p:first-of-type.

这篇关于:第n个孩子奇怪的行为与h1和p的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆