:nth-last-child() 這個CSS 偽類 從兄弟節(jié)點(diǎn)中從后往前匹配處于某些位置的元素。注意: 這個偽類和 :nth-child 基本一致, 但它是從結(jié)尾計(jì)數(shù), 而不是從開始計(jì)數(shù).
指定table的tr背景色和字體效果:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(cainiaoplus.com)</title>
<style>
table {
border: 1px solid blue;
}
/* 選擇最后三個元素 */
tr:nth-last-child(-n+3) {
background-color: pink;
}
/* 選擇從第二項(xiàng)到最后一項(xiàng)的每個元素 */
tr:nth-last-child(n+2) {
color: blue;
}
/* 僅選擇倒數(shù)第二個元素 */
tr:nth-last-child(2) {
font-weight: 600;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td>第一行</td>
</tr>
<tr>
<td>第二行</td>
</tr>
<tr>
<td>第三行</td>
</tr>
<tr>
<td>第四行</td>
</tr>
<tr>
<td>第五行</td>
</tr>
</tbody>
</table>
</body>
</html>測試看看 ?/?:nth-last-child(n) 選擇器匹配屬于其元素的第 N 個子元素的每個元素,不論元素的類型,從最后一個子元素開始計(jì)數(shù)。
n可以是一個數(shù)字,一個關(guān)鍵字,或者一個公式。
提示: 請參閱:nth-last-of-type() 選擇器。該選擇器匹配父元素中的倒數(shù)第n個結(jié)構(gòu)子元素。
tr:nth-last-child(odd) or tr:nth-last-child(2n+1)
表示HTML表的倒數(shù)的奇數(shù)行:1、3、5等。
tr:nth-last-child(even) or tr:nth-last-child(2n)
表示HTML表的倒數(shù)的偶數(shù)行:2、4、6等。
:nth-last-child(7)
表示倒數(shù)第7個元素。
:nth-last-child(5n)
表示倒數(shù)的第5、10、15等元素。
:nth-last-child(3n+4)
表示倒數(shù)的第4、7、10、13等元素。
:nth-last-child(-n+3)
表示一組兄弟節(jié)點(diǎn)中的最后三個元素。
p:nth-last-child(n) or p:nth-last-child(n+1)
表示一組兄弟節(jié)點(diǎn)中的每個<p>元素。這與一個簡單的p選擇器相同。(由于n從0開始,而最后一個元素從1開始,n和n+1都會選擇相同的元素。)
p:nth-last-child(1) or p:nth-last-child(0n+1)
表示所有處于兄弟節(jié)點(diǎn)中倒數(shù)第一位的元素<p>。這與:last-child選擇器相同。
表格中的數(shù)字表示支持該屬性的第一個瀏覽器版本號。
| 選擇器 | |||||
|---|---|---|---|---|---|
| :nth-last-child() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
奇數(shù)和偶數(shù)是可以作為關(guān)鍵字使用用于相匹配的子元素,其索引是奇數(shù)或偶數(shù)。
在這里,我們?yōu)槠鏀?shù)和偶數(shù)的倒數(shù)p元素指定兩個不同的背景顏色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(cainiaoplus.com)</title>
<style>
p:nth-last-child(odd)
{
background:#ff0000;
}
p:nth-last-child(even)
{
background:#0000ff;
}
</style>
</head>
<body>
<p>第一個段落。</p>
<p>第二個段落。</p>
<p>第三個段落。</p>
<p><b>注意:</b> Internet Explorer 8 以及更早版本的瀏覽器不支持:nth-last-child() 選擇器.</p>
</body>
</html>測試看看 ?/?使用公式(an+ b).描述:a代表一個循環(huán)的大小,N是一個計(jì)數(shù)器(從0開始),以及b是偏移量。
在這里,我們對所有索引是3的倍數(shù)的倒數(shù)順序的p元素指定了背景顏色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(cainiaoplus.com)</title>
<style>
p:nth-last-child(3n+0)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>這是標(biāo)題</h1>
<p>第一個段落。</p>
<p>第二個段落。</p>
<p>第三個段落。</p>
<p>第四個段落。</p>
<p>第五個段落。</p>
<p>第六個段落。</p>
<p>第七個段落。</p>
<p>第八個段落。</p>
<p>第九個段落。</p>
<p><b>注意:</b> Internet Explorer 8 以及更早版本的瀏覽器不支持 :nth-last-child()選擇器.</p>
</body>
</html>測試看看 ?/?