:nth-last-of-type(n) 用于从父元素末尾开始选择倒数第 n 个指定标签类型的子元素。例如 p:nth-last-of-type(1) 选中最后一个 p 元素,li:nth-last-of-type(2) 选中倒数第二个 li。结合 CSS 计数器可实现倒序编号:通过 counter-reset 定义计数器,counter-increment 设为 -1 实现递减,再用 ::before 插入编号。也可对末尾元素单独设置样式,如 p:nth-last-of-type(-n+2) 隐藏最后两个段落,li:nth-last-of-type(-n+3) 为倒数前三项添加红色边框,button:nth-last-of-type(2) 单独设置倒数第二个按钮背景色。支持公式 an+b,如 tr:nth-last-of-type(2n) 选中倒数偶数行,div:nth-last-of-type(3n+1) 从倒数第一项起每三项选一项。该选择器按元素类型从后向前匹配,适用于动态内容末尾的样式控制,关键在于理解其基于类型和逆向计数的机制。

使用 :nth-last-of-type 可以从父元素的最后一个子元素开始反向计数,为倒数第几个匹配类型的元素设置样式。它常用于实现倒序排列的视觉效果或特定位置的样式控制。
:nth-last-of-type(n) 选择器会选中其父元素中倒数第 n 个指定类型的元素。这里的“类型”指的是标签名,比如 p、div、li 等。
例如:
p:nth-last-of-type(1):选中最后一个 <p> 元素li:nth-last-of-type(2):选中倒数第二个 <li> 元素如果想让列表项显示为倒序编号(如 5,4,3,2,1),可以用 CSS 计数器配合 :nth-last-of-type 实现。
立即学习“前端免费学习笔记(深入)”;
pre{ counter-reset: section; } li { counter-increment: section -1; } li::before { content: "No." counter(section); }这里虽然没有直接用 :nth-last-of-type 控制顺序,但它可以用来对倒数位置的元素单独设置样式,比如高亮最后三项。
常见需求是给最后几个元素添加不同颜色或隐藏处理。
p:nth-last-of-type(-n+2) { display: none; }
li:nth-last-of-type(-n+3) { border: 1px solid red; }
button:nth-last-of-type(2) { background: yellow; }
:nth-last-of-type(an + b) 支持数学表达式,可用于更复杂的选择。
例如:
tr:nth-last-of-type(2n):选中倒数第偶数行的表格行div:nth-last-of-type(3n+1):从倒数第一项开始,每3项选一个基本上就这些。通过合理使用 :nth-last-of-type,你可以轻松实现基于倒序位置的样式控制,特别适合动态内容末尾的视觉调整。关键是理解它是按类型从后往前数的。不复杂但容易忽略细节。
以上就是如何用css :nth-last-of-type实现倒序样式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号