?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
E:nth-last-child(n) { sRules }
要使該屬性生效,E元素必須是某個元素的子元素,E的父元素最高是body,即E可以是body的子元素
該選擇符允許使用一個乘法因子(n)來作為換算方式,比如我們想選中倒數(shù)第一個子元素E,那么選擇符可以寫成:E:nth-last-child(1)
有一點需要注意的是:
HTML示例代碼:
<div> <p>第1個p</p> <p>第2個p</p> <span>第1個span</span> <p>第3個p</p> <span>第2個span</span> </div>
如上HTML,假設(shè)要命中倒數(shù)第一個p(即正數(shù)第3個p),那么CSS選擇符應(yīng)該是:
p:nth-last-child(2){color:#f00;}
而不是:
p:nth-last-child(1){color:#f00;}
因為倒數(shù)第1個p,其實是倒數(shù)第2個子元素。基于選擇符從右到左解析,首先要找到第1個子元素,然后再去檢查該子元素是否為p,如果不是p,則n遞增,繼續(xù)查找
假設(shè)不確定倒數(shù)第1個子元素是否為E,但是又想命中倒數(shù)第1個E,應(yīng)該這樣寫:
p:last-of-type{color:#f00;}
或者這樣寫:
p:nth-last-of-type(1){color:#f00;}
參考 E:last-of-type 和 E:nth-last-of-type(n)
IE | Firefox | Chrome | Safari | Opera | iOS Safari | Android Browser | Android Chrome |
---|---|---|---|---|---|---|---|
6.0-8.0 | 2.0+ | 4.0+ | 3.1+ | 3.5+ | 3.2+ | 2.1+ | 18.0+ |
IE9.0+ |
<!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="utf-8" /> <title>結(jié)構(gòu)性偽類選擇符 E:nth-last-child(n)_CSS參考手冊_web前端開發(fā)參考手冊系列</title> <meta name="author" content="Joy Du(飄零霧雨), dooyoe@gmail.com, www.doyoe.com" /> <style> h1 { font-size: 16px; } li:nth-last-child(1) { color: #f00; } </style> </head> <body> <h1>最后一行要變成紅色 <code>li:nth-last-child(1){color:#f00;}</code></h1> <ul> <li>結(jié)構(gòu)性偽類選擇符 E:nth-last-child(n)</li> <li>結(jié)構(gòu)性偽類選擇符 E:nth-last-child(n)</li> <li>結(jié)構(gòu)性偽類選擇符 E:nth-last-child(n)</li> </ul> </body> </html>
點擊 "運行實例" 按鈕查看在線實例