1. 程式人生 > >CSS3偽類選擇器nth-child和nth-of-type淺析

CSS3偽類選擇器nth-child和nth-of-type淺析

1. nth-child

定義和用法
:nth-child(n) 選擇器匹配屬於其父元素的第 n 個子元素,不論元素的型別。n 可以是數字、關鍵詞或公式。

① n為數字時,n為大於0的整數

.box :nth-child(1){background-color: red;}
<div class="box">
    <div>1-1</div>  
    <div>2-2</div>
</div>

這裡寫圖片描述

② n為關鍵字,even(偶數,等價於2n)、odd(奇數,等價於2n+1)

.box :nth-child(odd)
{background-color: red;} .box :nth-child(even){background-color: green;}

這裡寫圖片描述

③ n為公式
例如:,n+4(大於等於4),-n+5(小於等於5),3n+1(隔二取一)等

.box :nth-child(n+4){background-color: red;}
.box :nth-child(-n+2){background-color: green;}

這裡寫圖片描述

④ 其他, nth-last-child倒數第幾個

.box :nth-last-child(3){background-color: green
;}

這裡寫圖片描述

2. nth-of-type

定義和用法
:nth-of-type(n) 選擇器匹配屬於父元素的特定型別的第 N 個子元素的每個元素。n 可以是數字、關鍵詞或公式。

nth-of-type(n)和nth-child(n)的用法類似,不過nth-of-type(n)必須指定子元素的標籤型別

nth-child與nth-of-type的區別
nth-child(n)是子元素的第n個,tagName:nth-of-type(n)子元素中標籤名為tagName的第n個。

.box p:nth-of-type(1){background-color: red;}
.box div:nth-of-type(2){background-color:green;} .box div:nth-child(2){background-color:yellow;}
<div class="box">
    <p>我是第一個段落</p>
    <div>1-1</div>  
    <div>2-2</div>
</div>

這裡寫圖片描述

3. 小結

選擇器 數字 關鍵字 公式
nth-child 大於0的整數 even(2n), odd(2n+1) 3n+1,4+n,-n+2
nth-last-child 大於0的整數
nth-of-type 大於0的整數 even(2n), odd(2n+1) 3n+1,4+n,-n+2