记录一下自己因为概念不理解导致使用first-of-type和last-of-type错误的问题。这里以first-of-type为例,last-of-type同理。
先看下MDN上面对first-of-type的定义。
<div class="container">
<p class="p-box"></p>
<div></div>
<p class="p-box"></p>
<div class="box"></div>
<div class="box"></div>
</div>
.container {
background: skyblue;
width: 400px;
overflow: auto;
padding: 20px;
}
.container * {
background: pink;
width: 100px;
height: 100px;
margin-top: 20px;
}
.container :first-of-type {
background: lightgray;
}
所以根据定义,上面代码中的
.container :first-of-type {
background: lightgray;
}
**会先找到class为container子元素所有的类型(p和div两种)**然后找到这两种类型的第一个元素,把背景色设置为lightgray。
同理:
.container .box:first-of-type {
background: lightgray;
}
先找到class为container子元素的所有类型,然后找到两种类型的第一个元素,并且该元素的class为box。
第一个p元素class为p-box,第一个div元素class为空,所以.box:first-of-type
没有匹配到任何元素。
如果把标签改为这样:
<div class="container">
<p class="p-box"></p>
<p class="p-box"></p>
<div class="box"></div>
<div></div>
<div class="box"></div>
</div>
则效果为:
先找到container的所有子元素的类型(p和div),然后分别找到第一个p和第一个div中class为box的元素。
总结:first-of-type 是先找到所有标签类型中的第一个,然后再根据选择器匹配满足条件的元素。(last-of-type同理)