?
This document uses PHP Chinese website manual Release
語法:
E:nth-child(n) { sRules }
要使該屬性生效,E元素必須是某個元素的子元素,E的父元素最高是body,即E可以是body的子元素
該選擇符允許使用一個乘法因子(n)來作為換算方式,比如我們想選中所有的偶數(shù)子元素E,那么選擇符可以寫成:E:nth-child(2n)
使用E:nth-child(n)實現(xiàn)奇偶:
示例代碼:
<style> li:nth-child(2n){color:#f00;} /* 偶數(shù) */ li:nth-child(2n+1){color:#000;} /* 奇數(shù) */ </style> <ul> <li>列表項一</li> <li>列表項二</li> <li>列表項三</li> <li>列表項四</li> </ul>
因為(n)代表一個乘法因子,可以是0, 1, 2, 3, ..., 所以(2n)換算出來會是偶數(shù),而(2n+1)換算出來會是奇數(shù)
列表項一
列表項二
列表項三
列表項四
該選擇符允許使用一些關(guān)鍵字,比如:odd, even
使用odd, even實現(xiàn)奇偶:
<style> li:nth-child(even){color:#f00;} /* 偶數(shù) */ li:nth-child(odd){color:#000;} /* 奇數(shù) */ </style> <ul> <li>列表項一</li> <li>列表項二</li> <li>列表項三</li> <li>列表項四</li> </ul>
關(guān)鍵字odd代表奇數(shù),even代表偶數(shù)
列表項一
列表項二
列表項三
列表項四
有一點需要注意的是:
HTML示例代碼:
<div> <p>第1個p</p> <p>第2個p</p> <span>第1個span</span> <p>第3個p</p> <span>第2個span</span> <p>第4個p</p> <p>第5個p</p> </div>
CSS Case 1:
p:nth-child(2){color:#f00;}
很明顯第2個p會被命中然后變成紅色
CSS Case 2:
p:nth-child(3){color:#f00;}
這是會命中第3個p么?如果你這么認為那就錯了,這條選擇符就不會命中任何一個元素。
CSS Case 3:
p:nth-child(4){color:#f00;}
這時你以為會命中第4個p,但其實命中的卻是第3個p,因為它是第4個子元素
E:nth-child(n)會選擇父元素的第n個子元素E,如果第n個子元素不是E,則是無效選擇符,但n會遞增。
假設(shè)不確定第1個子元素是否為E,但是又想命中第1個E,應(yīng)該這樣寫:
p:first-of-type{color:#f00;}
或者這樣寫:
p:nth-of-type(1){color:#f00;}
參考 E:first-of-type 和 E:nth-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-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-child(2) { color: #f00; } </style> </head> <body> <h1>第二行要變成紅色 <code>li:nth-child(2){color:#f00;}</code></h1> <ul> <li>結(jié)構(gòu)性偽類選擇符 E:nth-child(n)</li> <li>結(jié)構(gòu)性偽類選擇符 E:nth-child(n)</li> <li>結(jié)構(gòu)性偽類選擇符 E:nth-child(n)</li> </ul> </body> </html>
點擊 "運行實例" 按鈕查看在線實例