:nth-child(n)
:nth-last-child(n)
:first-child
:last-child
:only-child
:nth-of-type(n)
:nth-last-of-type(n)
:first-of-type
:last-of-type
:only-of-type
:root
:empty
- :nth-child(n)
<style>
h4:nth-child(1) {background-color: red}
h5:nth-child(1) {background-color: green}
</style>
<body>
<h6>0-0</h6>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
<h4>1-2</h4>
<h4>1-3</h4>
<h5>1-4</h5>
</div>
</body>
匹配第n個元素飒硅,n
是從1
開始的,而不是0
胁出,位置不區(qū)分同級元素類型。
- :nth-last-child(n)
<style>
h4:nth-last-child(1) {background-color: red}
h5:nth-last-child(1) {background-color: green}
</style>
<body>
<h6>0-0</h6>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
<h4>1-2</h4>
<h4>1-3</h4>
<h5>1-4</h5>
</div>
</body>
倒敘地匹配第n個元素段审,n
是從1
開始的划鸽,而不是0
,位置不區(qū)分同級元素類型戚哎。
:first-child 等同于 :nth-child(1)。
:last-child 等同于 :nth-last-child(1)嫂用。
:only-child
<style>
h4:only-child {background-color: green}
</style>
<body>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
</div>
<div>
<h4>2-0</h4>
</div>
</body>
僅當(dāng)元素在其父元素中是唯一一個子元素時型凳,才匹配該子元素,位置不區(qū)分同級元素類型嘱函。
- :nth-of-type(n)
<style>
h5:nth-of-type(1) {background-color: red}
h4:nth-of-type(1) {background-color: green}
</style>
<body>
<h6>0-0</h6>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
<h4>1-2</h4>
<h4>1-3</h4>
<h5>1-4</h5>
</div>
</body>
匹配元素在同級而且相同元素中第n
次出現(xiàn)的元素甘畅,n
是從1
開始的,而不是0
。
image.png
- :nth-last-of-type(n)
<style>
h5:nth-last-of-type(1) {background-color: red}
h4:nth-last-of-type(1) {background-color: green}
</style>
<body>
<h6>0-0</h6>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
<h4>1-2</h4>
<h4>1-3</h4>
<h5>1-4</h5>
</div>
</body>
倒敘地匹配元素在同級而且相同元素中第n
次出現(xiàn)的元素疏唾,n
是從1
開始的蓄氧,而不是0
。
:first-of-type 等同于 :nth-of-type(1)槐脏。
:last-of-type 等同于 :nth-last-of-type(1) 喉童。
:only-of-type
<style>
h4:only-of-type {background-color: green}
</style>
<body>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
</div>
<div>
<h4>2-0</h4>
</div>
</body>
僅當(dāng)該元素在其父元素中僅有唯一一個該元素時,才匹配該元素顿天。
- :root
<style>
:root {background-color: green}
h4:root {background-color: red}
</style>
<body>
<h6>0-0</h6>
<div>
<h5>1-0</h5>
<h4>1-1</h4>
<h4>1-2</h4>
<h4>1-3</h4>
<h5>1-4</h5>
</div>
</body>
:root
始終指向<html>
標(biāo)簽堂氯,不要試圖在選擇器前面加上元素,像這樣h4:root
牌废,它的意思是當(dāng)前頁面的頂級元素并且該元素為h4
標(biāo)簽時匹配咽白。
- :empty
<style>
div:empty {background-color: green; height: 20px;}
</style>
<body>
<div></div>
<div>
<h4>2-0</h4>
</div>
<div>3-0</div>
</body>
僅當(dāng)元素內(nèi)部沒有子元素和文本時,匹配該元素鸟缕。
總結(jié)
-
...-child
與...-of-type
的區(qū)別:-child
統(tǒng)計時不論元素種類晶框,只論元素位置;-of-type
統(tǒng)計時會先區(qū)分元素種類懂从,再查詢當(dāng)前種類下的位置授段。 -
n
可以是正整數(shù)(1、2莫绣、3)畴蒲,表示第一、第二对室、第三位模燥;可以是n
本身(n),表示匹配所有位置掩宜;可以是n
和算術(shù)(2n-1)蔫骂,表示匹配基數(shù)或者更靈活的;也可以是字符串odd
和even
(odd牺汤、even)辽旋,分別表示匹配奇數(shù)位置和偶數(shù)位置。