CSS :nth-last-child() 偽類
- 上一頁 :nth-child()
- 下一頁 :nth-last-of-type()
- 返回上一層 CSS 偽類參考手冊
定義和用法
CSS :nth-last-child(n)
偽類用于匹配作為其父元素倒數第 n 個子元素的每個元素,無論其類型如何。
n 可以是一個數字/索引、一個關鍵字(odd
或 even
)或一個公式(如 an + b)。
提示:查看 :nth-last-of-type()
偽類以選擇作為其父元素中指定類型的倒數第 n 個子元素的元素。
實例
例子 1
為每個作為其父元素倒數第二個子元素的 <p> 元素指定背景顏色:
p:nth-last-child(2) { background-color: red; }
例子 2
odd
和 even
是關鍵字,可用于匹配索引為奇數或偶數的子元素。
在這里,我們為倒數索引為奇數和偶數的 <p> 元素指定不同的背景顏色:
p:nth-last-child(odd) { background-color: red; } p:nth-last-child(even) { background-color: blue; }
例子 3
使用公式(an + b)。描述:a 表示整數步長,n 是從 0 開始的所有非負整數,b 是整數偏移量。
在這里,我們為倒數索引是 3 的倍數的所有 <p> 元素指定背景顏色:
p:nth-last-child(3n+0) { background-color: red; }
CSS 語法
:nth-last-child(index | odd | even | an+b) { css declarations; }
技術細節
版本: | CSS3 |
---|
瀏覽器支持
表格中的數字指定了完全支持該偽類的首個瀏覽器版本。
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
- 上一頁 :nth-child()
- 下一頁 :nth-last-of-type()
- 返回上一層 CSS 偽類參考手冊