记录一下自己因为概念不理解导致使用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同理)
理解CSS选择器first-of-type和last-of-type的误用示例

文章通过一个例子解释了CSS选择器first-of-type的工作原理,指出它首先找到所有不同类型的元素,然后在这些类型中选取第一个元素。last-of-type的逻辑与其相反。当使用.container:first-of-type时,它将作用于.container内的首个元素,而不是.class为box的第一个元素。文章强调了理解元素类型和选择器匹配的重要性。
3451

被折叠的 条评论
为什么被折叠?



