css选择器:last-child与last-of-type区别

:last-child 选择父元素中最后一个且符合指定类型的子元素,而 :last-of-type 选择父元素中该类型最后一个元素;例如在包含 p、p、span 的 div 中,p:last-child 不匹配(最后是 span),但 p:last-of-type 会匹配第二个 p。

css选择器:last-child与last-of-type区别

:last-child:last-of-type 都是CSS中的伪类选择器,用来选中特定位置的元素,但它们的匹配逻辑不同,容易混淆。下面详细说明两者的区别。

:last-child 选择器

这个选择器匹配的是父元素中的最后一个子元素,并且该元素必须符合选择器指定的类型。

换句话说,只有当目标元素既是最后一个子节点,又是所选标签时,才会被选中。

例如:

假设HTML结构如下:

<div>
  <p>段落1</p>
  <p>段落2</p>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/1337">
                            <img src="https://img.php.cn/upload/ai_manual/001/431/639/68b6d64b79043646.png" alt="盘古大模型">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/1337">盘古大模型</a>
                            <p>华为云推出的一系列高性能人工智能大模型</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="盘古大模型">
                                <span>207</span>
                            </div>
                        </div>
                        <a href="/ai/1337" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="盘古大模型">
                        </a>
                    </div>
                
  <span>文本</span>
</div>

使用 p:last-child 不会选中任何元素,因为最后一个子元素是 <span></span>,不是 <p></p>

但如果结构是:

<div>
  <p>段落1</p>
  <p>段落2</p>
</div>

那么 p:last-child 就会选中第二个 <p></p>,因为它是最后一个子元素,且是 p 标签。

:last-of-type 选择器

这个选择器匹配的是父元素中,不关心它是否是所有子元素中的最后一个。

只要它是某一类标签(如 p、div、span)中排在最后的一个,就会被选中。

继续上面第一个例子:
<div>
  <p>段落1</p>
  <p>段落2</p>
  <span>文本</span>
</div>

使用 p:last-of-type 会选中第二个 <p></p>,因为它是所有 p 标签中的最后一个,即使后面还有一个 span

span:last-of-type 会选中那个 span 元素,因为它是唯一一个 span 类型,自然也是最后一个。

关键区别总结

  • :last-child 关注的是“是否为最后一个子元素”,要求位置和类型都满足。
  • :last-of-type 关注的是“是否为某类标签的最后一个”,只看标签类型,不强制要求是整体最后一个。
  • 如果最后一个子元素恰好是目标类型,:last-child 和 :last-of-type 可能选中同一个元素。
  • 当目标类型后面还有其他类型的元素时,:last-child 失效,:last-of-type 仍可生效。

基本上就这些。理解清楚两者的判断依据,就能准确选择需要的元素。实际使用中,:last-of-type 更灵活,尤其在子元素类型混杂时更实用。

以上就是css选择器:last-child与last-of-type区别的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。