:last-of-type 能精准选中父元素下同类型子元素的最后一个,比 :last-child 更灵活。例如 p:last-of-type 可成功匹配末尾的 元素,即使其后还有其他标签;常用于去除列表最后一项的分隔线,如 li:last-of-type { border-bottom: none; },即便列表中混入非 元素也能正确应用;还可与其他伪类组合使用,如 div p:last-of-type 设置块内最后一个段落样式,或 article img:last-of-type 调整图片间距,结合 :not() 排除最后一项更显简洁。需注意该选择器基于元素类型匹配,仅在直接子元素中查找,空或隐藏元素仍被计入。掌握其“同类型最后位置”特性可减少类名依赖,提升样式适应性。

:last-of-type 是 CSS 中一个非常实用的伪类选择器,它能选中父元素下同类型中的最后一个子元素。这个选择器在处理动态内容或不规则结构时特别有用。下面介绍几种常见的使用技巧,帮助你更高效地运用 :last-of-type。
当你需要为某一类标签(如 p、li、div)的最后一个实例设置特殊样式时,:last-of-type 比 :last-child 更灵活,因为它只关心“类型”和“位置”,而不强制该元素是父容器的最后一个子节点。
比如,有如下 HTML:<div> <p>段落1</p> <p>段落2</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> <span>其他内容</span> </div>
p:last-child,将无法匹配任何元素,因为 <p></p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/2194">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680269459383.png" alt="MacsMind">
</a>
<div class="aritcle_card_info">
<a href="/ai/2194">MacsMind</a>
<p>电商AI超级智能客服</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="MacsMind">
<span>192</span>
</div>
</div>
<a href="/ai/2194" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="MacsMind">
</a>
</div>
不是最后一个子元素。但使用:
p:last-of-type {
color: red;
}<p></p>,即使后面还有 <span></span>。
常见于导航菜单或文章列表,每个项目之间用边框或下划线分隔,但最后一个项目不需要分隔线。
<ul> <li>首页</li> <li>关于</li> <li>联系</li> </ul>
li {
border-bottom: 1px solid #ccc;
padding: 8px 0;
}
li:last-of-type {
border-bottom: none;
}li:last-child,:last-of-type 更安全,尤其当 <ul></ul> 内部可能混入其他标签(如注释容器)时依然有效。
:last-of-type 可与其他伪类组合使用,提升选择精度。
例如,只想选中块级元素中的最后一个段落:div p:last-of-type {
margin-bottom: 0;
}<img alt="css伪类:last-of-type选择器使用技巧" > 添加边距:
article img:last-of-type {
margin-right: 0;
}p:not(:last-of-type) {
margin-bottom: 1em;
}:last-of-type 是按元素类型匹配的,也就是说:
•p:last-of-type 只会找最后一个 <p></p>
• 如果父元素中有多个类型,每个类型都可能有自己的“最后一个”
• 它不会跨父级作用,只能在直接子元素中查找
• 空元素或隐藏元素仍会被计算在内,除非从 DOM 移除
基本上就这些。掌握 :last-of-type 的核心在于理解“同类型”和“最后位置”的关系,合理使用可以减少 HTML 类名依赖,让样式更具适应性。
以上就是css伪类:last-of-type选择器使用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号