first-of-type、last-of-type与class一起使用不生效的问题

记录一下自己因为概念不理解导致使用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同理)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值