前端常见bug系列1:容易被误解的:last-child 和 :first-child

用某个选择器过滤出来一个元素集合,当我们想选中最后一个元素的时候,是不是很容易想到:last-child?比如,有下面一段CSS和HTML片段:

<style>
        .section{
            margin-bottom: 50px;
        }

        .section1-item:last-child{
            color: blue;
        }
</style>
<section class="section section1">
        <header>header</header>
        <p class="section1-item card">111</p>
        <p class="section1-item card">222</p>
        <p class="section1-item card">333</p>
        <p class="section1-item card">444</p>
        <footer>footer</footer>
</section>

本来是想选中<p class="section1-item card">444</p>给它设置颜色为蓝色的,结果什么也没有发生。为什么?

查看W3C的相关介绍

The :last-child pseudo-class represents an element that is the last child of some other element.

someselecttor:last-chid 所表示的是,如果someselecttor所选中的某个节点恰好是其父元素的最后一个直接子节点,那么该选择器生效。而不是表示someselecttor选中的节点集合的最后一个。

同理,我们马上可以想到,:first-child是不是也有类似问题?添加一句样式.section1-item:last-child{ color: red; }到上面的例子中一试就知道,问题果然存在。

someselecttor:first-chid 所表示的是如果someselecttor所选中的某个节点恰好是其父元素的第一个直接子节点,那么该选择器生效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值