这个伪类要站在子元素的角度来看,来看看是不是父元素的第一个。
:first-child选择器是css2中定义的选择器,从字面意思上来看也很好理解,就是第一个子元素。比如有段代码:
针对p:first-child新的理解:
p:first-child
匹配到的是p元素,因为p元素是div的第一个子元素;
p:first-child 等价于 div p:first-child,等价于p是否是div下的元素且是第一个元素,如果是,则匹配上,如果不是,则匹配不上。
同理:
.summary-card-content .summary-card-description:nth-of-type(4) { }
会匹配summary-card-content下的summary-card-description,且summary-card-description是summary-card-content下的第四个元素
h1:first-child
匹配不到任何元素,因为在这里h1是div的第二个子元素,而不是第一个;
span:first-child
匹配不到任何元素,因为在这里两个span元素都不是div的第一个子元素;
然后,在css3中又定义了:first-of-type这个选择器,这个跟:first-child有什么区别呢?还是看那段代码:
p:first-of-type
匹配到的是p元素,因为p是div的所有类型为p的子元素中的第一个;
h1:first-of-type
匹配到的是h1元素,因为h1是div的所有类型为h1的子元素中的第一个;
span:first-of-type
匹配到的是第三个子元素span。这里div有两个为span的子元素,匹配到的是它们中的第一个。
所以,通过以上两个例子可以得出结论:
:first-child 匹配的是某父元素的第一个子元素,可以说是结构上的第一个子元素。
:first-of-type 匹配的是某父元素下相同类型子元素中的第一个,比如 p:first-of-type,就是指所有类型为p的子元素中的第一个。这里不再限制是第一个子元素了,只要是该类型元素的第一个就行了。
同样类型的选择器 :last-child 和 :last-of-type、:nth-child(n) 和 :nth-of-type(n) 也可以这样去理解。
举例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
p:first-of-type{
color:red;
}
div:first-of-type {
color: green;
}
/* p:first-child{
color:red;
}
div:first-child {
color: green;
} */
</style>
</head>
<body>
<header class="wrapper">
<p>aaa</p>
<p>bbbb</p>
<p>ddd</p>
<div>kkk</div>
<div>nnn</div>
</header>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* p:first-of-type{
color:red;
}
div:first-of-type {
color: green;
} */
p:first-child{
color:red;
}
div:first-child {
color: green;
}
</style>
</head>
<body>
<header class="wrapper">
<p>aaa</p>
<p>bbbb</p>
<p>ddd</p>
<div>kkk</div>
<div>nnn</div>
</header>
</body>
</html>