:last-of-type 选择同类型标签的最后一个元素,而 :nth-last-child(n) 从末尾倒数第 n 个子元素开始匹配;两者可组合使用以实现更精准的样式控制。

在 CSS 中,
:last-of-type
:nth-last-child()
:last-of-type 选择的是其父元素中同类型标签的最后一个元素。比如多个
p
p
p:last-of-type
<p>
<div>
<span>
:nth-last-child(n) 从父元素的最后一个子元素开始倒数,匹配倒数第 n 个子元素,且必须是同级的直接子元素。
立即学习“前端免费学习笔记(深入)”;
常见用法::nth-last-child(1)
:last-child
:nth-last-child(2)
:nth-last-child(odd)
可以!将
:last-of-type
:nth-last-child()
你想选中既是某种类型最后一个,又处于倒数第几个位置的元素。
比如:
p:last-of-type:nth-last-child(2) {
color: red;
}这行 CSS 的意思是:选中同时满足两个条件的
p
p
:last-of-type
:nth-last-child(2)
只有当同一个
p
这类组合常用于结构固定的模块,比如文章末尾的提示段落或评论列表的最后一项。
举个例子:假设你有一组动态内容,希望当最后一个段落恰好是倒数第二个子元素时,给它加边框:
.content p:last-of-type:nth-last-child(2) {
border-bottom: 1px solid #ccc;
padding-bottom: 10px;
}这样可以避免对真正最后一个元素(可能是按钮或图片)应用不该有的样式。
基本上就这些。关键是理解两者判断依据不同:
:last-of-type
:nth-last-child
以上就是如何用css:last-of-type和nth-last-child组合的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号