
:nth-last-child() 这个CSS 伪类 从兄弟节点中从后往前匹配处于某些位置的元素。注意: 这个伪类和 :nth-child 基本一致, 但它是从结尾计数, 而不是从开始计数.
在线示例
指定table的tr背景色和字体效果:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>大卫编程网(div.cn)</title>
<style>
table {
border: 1px solid blue;
}
/* 选择最后三个元素 */
tr:nth-last-child(-n+3) {
background-color: pink;
}
/* 选择从第二项到最后一项的每个元素 */
tr:nth-last-child(n+2) {
color: blue;
}
/* 仅选择倒数第二个元素 */
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 个子元素的每个元素,不论元素的类型,从最后一个子元素开始计数。
n可以是一个数字,一个关键字,或者一个公式。
提示: 请参阅:nth-last-of-type() 选择器。该选择器匹配父元素中的倒数第n个结构子元素。
选择器示例
tr:nth-last-child(odd) or tr:nth-last-child(2n+1)
表示HTML表的倒数的奇数行:1、3、5等。
tr:nth-last-child(even) or tr:nth-last-child(2n)
表示HTML表的倒数的偶数行:2、4、6等。
:nth-last-child(7)
表示倒数第7个元素。
:nth-last-child(5n)
表示倒数的第5、10、15等元素。
:nth-last-child(3n+4)
表示倒数的第4、7、10、13等元素。
:nth-last-child(-n+3)
表示一组兄弟节点中的最后三个元素。
p:nth-last-child(n) or p:nth-last-child(n+1)
表示一组兄弟节点中的每个<p>元素。这与一个简单的p选择器相同。(由于n从0开始,而最后一个元素从1开始,n和n+1都会选择相同的元素。)
p:nth-last-child(1) or p:nth-last-child(0n+1)
表示所有处于兄弟节点中倒数第一位的元素<p>。这与:last-child选择器相同。
浏览器兼容性
表格中的数字表示支持该属性的第一个浏览器版本号。
| 选择器 | |||||
|---|---|---|---|---|---|
| :nth-last-child() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
示例 1
奇数和偶数是可以作为关键字使用用于相匹配的子元素,其索引是奇数或偶数。
在这里,我们为奇数和偶数的倒数p元素指定两个不同的背景颜色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>大卫编程网(div.cn)</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>测试看看 ‹/›示例 2
使用公式(an+ b).描述:a代表一个循环的大小,N是一个计数器(从0开始),以及b是偏移量。
在这里,我们对所有索引是3的倍数的倒数顺序的p元素指定了背景颜色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>大卫编程网(div.cn)</title>
<style>
p:nth-last-child(3n+0)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</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>测试看看 ‹/›