CSS :nth-last-of-type() 伪类
示例
为父元素中从末尾数起的第二个 <p> 元素设置背景色。同时,为父元素中从末尾数起的第三个 <li> 元素设置背景色。
p:nth-last-of-type(2) {
background: red;
}
li:nth-last-of-type(3) {
background: yellow;
}
自己动手试一试 »
更多“自己尝试”的例子见下文。
定义和用法
伪类 :nth-last-of-type(n)
匹配其父元素中,按类型分组后,从最后开始数的第 n 个元素。
n 可以是数字/索引、关键字(odd 或 even)或公式(如 an + b)。
提示: 查看 :nth-last-child() 伪类,它选择其父元素中,无论类型如何,从最后开始数的第 n 个子元素。
版本 | CSS3 |
---|
浏览器支持
表中数字表示该伪类完全支持的第一个浏览器版本。
伪类 | |||||
---|---|---|---|---|---|
:nth-last-of-type() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
CSS 语法
更多示例
示例
odd 和 even 是关键字,可以用来匹配索引为奇数或偶数的子元素(第一个子元素的索引为 1)。
这里,我们为奇数和偶数 p 元素指定了两种不同的背景颜色
p:nth-last-of-type(odd) {
background: red;
}
p:nth-last-of-type(even) {
background: blue;
}
自己动手试一试 »
示例
使用公式(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;
}
自己动手试一试 »