您好,登錄后才能下訂單哦!
今天就講一下css選擇器:nth-child()和:nth-of-type()的使用。
一、:nth-child()和:nth-of-type()的支持度
所有主流瀏覽器均支持:nth-child()和:nth-of-type()選擇器,除了 IE8 及更早的版本。
二、:nth-child()和:nth-of-type()的一般使用方法
1、:nth-child(x); 選擇第x的元素
2、:nth-child(x*n) x的n倍元素
3、:nth-child(n+x); 選擇 =>x 的元素
4、:nth-child(-n+x) 選擇 =< x 的元素
5、:nth-child(nx+1); nx-1 隔開(kāi)n*x選取一個(gè)
6、nth-child(odd)/nth-child(even) 奇數(shù)偶數(shù)
使用的時(shí)候請(qǐng)把《*》刪除
三、:nth-child()和:nth-of-type()的一些不同之處
:nth-child()—–》
混合型跳過(guò)模式:這個(gè)是我自己取得名字。
意思就是說(shuō)同一個(gè)父級(jí)下如果我們選擇了第二個(gè)元素p:nth-child(2)。
但是第二個(gè)元素不是p標(biāo)簽而是其他的標(biāo)簽,那么選擇的標(biāo)簽不成立,選擇不了。
代碼如下:
<div id="a1">
<p>CGLweb前端</p>
<div>CGLweb前端</div>
<p>CGLweb前端</p>
</div>
<style type="text/css">
#a1 p:nth-child(2){ background:#000000;}(www.gendna5.com)
</style>
:nth-of-type()—–》
匹配標(biāo)簽選擇模式,比如說(shuō)代碼div:nth-of-type(2n),不考慮其他的標(biāo)簽,
先把同級(jí)div排列一下,然后2的倍數(shù)的時(shí)候選擇他。
<div id="a2">
<p>p1</p>
<div>div1</div>
<p>p2</p>
<div>div2</div>
<div>div3</div>
<p>p3</p>
<div>div4</div>
<div>div5</div>
<div>div6</div>
</div>
<style type="text/css">
#a2 div:nth-of-type(2n){ background:#000000; color:#fff;}
</style>
四、一般使用方法
1、:nth-child(x); 選擇第x的元素
代碼:
<div class="div1">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
</div>
<style type="text/css">
.div1 p:nth-child(5){ background:#0086b3; color:#fff;}
</style>
2、:nth-child(x*n) x的n倍元素
代碼:
<div class="div2">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
</div>
<style type="text/css">
.div2 p:nth-child(2n){ background:#0086b3; color:#fff;}
</style>
3、:nth-child(n+x); 選擇 =>x 的元素
代碼:
<div class="div3">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
</div>
<style type="text/css">
.div3 p:nth-child(n+3){ background:#0086b3; color:#fff;}
</style>
4、:nth-child(-n+x) 選擇 =< x 的元素
代碼:
<div class="div4">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
</div>
<style type="text/css">
.div4 p:nth-child(-n+3){ background:#0086b3; color:#fff;}
</style>
5、:nth-child(nx+1); nx-1 隔開(kāi)n*x選取一個(gè)
代碼:
<div class="div5">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
</div>
<style type="text/css">
.div5 p:nth-child(3n+1){ background:#0086b3; color:#fff;}
</style>
6、nth-child(odd)/nth-child(even) 奇數(shù)偶數(shù)
代碼:
<div class="div6">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
</div>
<style type="text/css">
.div6 p:nth-child(odd){ background:#0086b3; color:#fff;}
.div6 p:nth-child(even){ background:#f4b613; color:#fff;}
</style>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。