css3 first-of-type选择器以及css3选择器中:first-child与:first-of-type的区别
CSS3 first-of-type选择器
“:first-of-type”选择器类似于“:first-child”选择器,不同之处就是指定了元素的类型,其主要用来定位一个父元素下的某个类型的第一个子元素。
示例演示:
通过“:first-of-type”选择器,定位div容器中的第一个p元素(p不一定是容器中的第一个子元素),并设置其背景色为橙色。
HTML代码:
<div class="wrapper"> <div>我是一个块元素,我是.wrapper的第一个子元素</div> <p>我是一个段落元素,我是不是.wrapper的第一个子元素,但是他的第一个段落元素</p> <p>我是一个段落元素</p> <div>我是一个块元素</div> </div>
CSS代码:
.wrapper {
width: 500px;
margin: 20px auto;
padding: 10px;
border: 1px solid #ccc;
color: #fff;
}
.wrapper > div {
background: green;
}
.wrapper > p {
background: blue;
}
/*我要改变第一个段落的背景为橙色*/
.wrapper > p:first-of-type {
background: orange;
}
演示结果:

区别:
:first-child 匹配的是某父元素的第一个子元素,可以说是结构上的第一个子元素。
:first-of-type 匹配的是某父元素下相同类型子元素中的第一个,比如 p:first-of-type,就是指所有类型为p的子元素中的第一个。这里不再限制是第一个子元素了,只要是该类型元素的第一个就行了。
也可以这么说:
:first-child 相当与 小明的爸爸的大孩子(全部孩子中的第一个)
:first-of-type 相当与小明的爸爸的大男孩(男孩中的第一个,也就是年纪最大的一个)
代码比较如下:
:first-child:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>:first-of-type</title>
<style type="text/css">
.wrapper {
border: 1px solid slateblue;
padding: 10px;
width: 500px;
margin: 20px auto;
}
.wrapper > p,
.wrapper > div {
margin: 10px 0;
background:deepskyblue;
color: #fff;
padding: 5px;
}
.wrapper>p:first-child {
background: blue;
}
</style>
</head>
<body>
<div class="wrapper">
<p>我是第一个段落</p>
<p>我是第二个段落</p>
<div>我是第一个Div元素</div>
<div>我是第二个Div元素</div>
<p>我是第三个段落</p>
<p>我是第四个段落</p>
<div>我是第三个Div元素</div>
<div>我是第四个Div元素</div>
</div>
</body>
</html>
效果:

:first-of-type
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>:first-of-type</title>
<style type="text/css">
.wrapper {
border: 1px solid slateblue;
padding: 10px;
width: 500px;
margin: 20px auto;
}
.wrapper > p,
.wrapper > div {
margin: 10px 0;
background:deepskyblue;
color: #fff;
padding: 5px;
}
.wrapper > div:first-of-type {
background: orange;
}
.wrapper>p:first-of-type{
background: salmon;
}
</style>
</head>
<body>
<div class="wrapper">
<p>我是第一个段落</p>
<p>我是第二个段落</p>
<div>我是第一个Div元素</div>
<div>我是第二个Div元素</div>
<p>我是第三个段落</p>
<p>我是第四个段落</p>
<div>我是第三个Div元素</div>
<div>我是第四个Div元素</div>
</div>
</body>
</html>
效果:

参考资料:http://www.imooc.com/code/809
越努力越幸运

浙公网安备 33010602011771号