CSS :nth-last-of-type() 伪类
定义和用法
CSS :nth-last-of-type(n)
伪类用于匹配作为其父元素中特定类型的倒数第 n 个子元素的每个元素。
n 可以是一个数字/索引、一个关键字(odd 或 even)或一个公式(如 an + b)。
提示:查看 :nth-last-child()
伪类以选择作为其父元素中倒数第 n 个子元素的元素,无论其类型如何。
实例
例子 1
为每个作为其父元素倒数第二个 <p> 元素的 <p> 元素指定背景颜色。
同时,为每个作为其父元素倒数第三个 <li> 元素的 <li> 元素指定背景颜色:
p:nth-last-of-type(2) { background: red; } li:nth-last-of-type(3) { background: yellow; }
例子 2
odd
和 even
是关键字,可用于匹配索引为奇数或偶数的子元素(第一个子元素的索引为 1)。
在这里,我们为奇数索引和偶数索引的 <p> 元素指定不同的背景颜色:
p:nth-last-of-type(odd) { background: red; } p:nth-last-of-type(even) { background: blue; }
例子 3
使用公式(an + b)。描述:a 表示整数步长,n 是从 0 开始的所有非负整数,b 是整数偏移量。
在这里,我们为倒数索引是 3 的倍数的所有 <p> 和 <li> 元素指定背景颜色:
p:nth-last-of-type(3n) { background: red; } li:nth-last-of-type(3n) { background: yellow; }
CSS 语法
:nth-last-of-type(index | odd | even | an+b) { css declarations; }
技术细节
版本: | CSS3 |
---|
浏览器支持
表格中的数字指定了完全支持该伪类的首个浏览器版本。
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
4.0 | 9.0 | 3.5 | 3.2 | 9.6 |