?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
E:nth-last-child(n) { sRules }
要使該屬性生效,E元素必須是某個(gè)元素的子元素,E的父元素最高是body,即E可以是body的子元素
該選擇符允許使用一個(gè)乘法因子(n)來(lái)作為換算方式,比如我們想選中倒數(shù)第一個(gè)子元素E,那么選擇符可以寫(xiě)成:E:nth-last-child(1)
有一點(diǎn)需要注意的是:
HTML示例代碼:
<div> <p>第1個(gè)p</p> <p>第2個(gè)p</p> <span>第1個(gè)span</span> <p>第3個(gè)p</p> <span>第2個(gè)span</span> </div>
如上HTML,假設(shè)要命中倒數(shù)第一個(gè)p(即正數(shù)第3個(gè)p),那么CSS選擇符應(yīng)該是:
p:nth-last-child(2){color:#f00;}
而不是:
p:nth-last-child(1){color:#f00;}
因?yàn)榈箶?shù)第1個(gè)p,其實(shí)是倒數(shù)第2個(gè)子元素。基于選擇符從右到左解析,首先要找到第1個(gè)子元素,然后再去檢查該子元素是否為p,如果不是p,則n遞增,繼續(xù)查找
假設(shè)不確定倒數(shù)第1個(gè)子元素是否為E,但是又想命中倒數(shù)第1個(gè)E,應(yīng)該這樣寫(xiě):
p:last-of-type{color:#f00;}
或者這樣寫(xiě):
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)性偽類(lèi)選擇符 E:nth-last-child(n)_CSS參考手冊(cè)_web前端開(kāi)發(fā)參考手冊(cè)系列</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)性偽類(lèi)選擇符 E:nth-last-child(n)</li> <li>結(jié)構(gòu)性偽類(lèi)選擇符 E:nth-last-child(n)</li> <li>結(jié)構(gòu)性偽類(lèi)選擇符 E:nth-last-child(n)</li> </ul> </body> </html>
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例