使用 :last-of-type 伪类可选择父元素中同类型标签的最后一个元素,例如 p:last-of-type 会选中最后一个段落标签,即使其后存在其他类型元素;在给定HTML中,p:last-of-type 将“段落3”设为红色,因其是所有 p 元素的最后一个;与 :last-child 不同,后者要求元素必须是父级的最后一个子节点且不区分类型,而 :nth-last-of-type(1) 则等效于 :last-of-type。

在CSS中选择最后一个特定类型的元素,可以使用 :last-of-type 伪类。它会选中父元素中同类型标签的最后一个元素。
:last-of-type 根据元素的类型(即标签名)来匹配其在父容器中的最后一个实例。例如:
p:last-of-type 会选择其父元素中最后一个 <p></p> 元素。
<li>
li:last-of-type 会选择列表中最后一个 <li> 元素(即使后面还有其他类型的元素)。
假设有如下HTML结构:
<div>
<p>段落1</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
<p>段落2</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1492">
<img src="https://img.php.cn/upload/ai_manual/001/431/639/68b6c7fc08309623.png" alt="Fotor AI Image Upscaler">
</a>
<div class="aritcle_card_info">
<a href="/ai/1492">Fotor AI Image Upscaler</a>
<p>Fotor推出的AI图片放大工具</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="Fotor AI Image Upscaler">
<span>73</span>
</div>
</div>
<a href="/ai/1492" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="Fotor AI Image Upscaler">
</a>
</div>
<span>文字内容</span>
<p>段落3</p>
</div>
使用以下CSS:
p:last-of-type {
color: red;
}
结果是“段落3”变成红色,因为它是所有 p 标签中的最后一个。
:last-of-type 是按元素类型选择最后一个,不同于:
:last-child:必须是父元素的最后一个子元素,且是唯一一个类型无关的“末尾”元素。
<li>
:nth-last-of-type(n):更灵活的方式,比如 :nth-last-of-type(1) 等同于 :last-of-type。
基本上就这些。使用 :last-of-type 能精准定位某类标签的末位元素,不依赖其是否为最后一个子节点,很实用。
以上就是在css中选择last-of-type元素方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号