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;
}
自己動手試一試 »