大网数据广告活动
Web 标准与前端开发

:nth-last-child

· 52CE 我爱测

**`:nth-last-child()`** 这个CSS 伪类从兄弟节点中从后往前匹配处于某些位置的元素

:nth-last-child() 这个CSS 伪类从兄弟节点中从后往前匹配处于某些位置的元素

/* 在所有兄弟节点中,从后往前
   选择所有 4 的倍数的节点 */
:nth-last-child(4n) {
  color: lime;
}

[!NOTE] 这个伪类和 :nth-child 基本一致,但它是从结尾计数,而不是从开始计数。

语法

nth-last-child伪类接受一个参数,用来作为一个模式,从后往前匹配元素。

关键字值

  • odd
    • : 代表一些元素,它们在所在的兄弟节点中,从后往前计算的数字位置是奇数,比如:1, 3, 5 等。
  • even
    • : 代表一些元素,它们在所在的兄弟节点中,从后往前计算的数字位置是偶数,比如:2, 4, 6 等。

函数符号

  • <An+B>
    • : 代表一些元素,它们在所在兄弟节点中的数字位置满足模式 An+B, n是 0 或者任意的正整数。从结尾开始计算的第一个元素的索引值是1. A 和 B 必须都是 <integer>。

of <selector> 语法

通过传递一个选择器参数,我们可以选择与该选择器匹配的倒数第 n 个元素。例如,以下选择器会匹配最后三个被赋予 class="important" 的 important 列表项。

:nth-last-child(-n + 3 of li.important) {
}

[!NOTE] 这与将选择器移到函数外部不同,例如:

li.important:nth-last-child(-n + 3) {
}

如果列表项位于最后三个子项之中,则该选择器会为其应用样式。

示例

选择器示例

  • 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选择器相同。

列表示例

HTML

<table>
  <tbody>
    <tr>
      <td>First line</td>
    </tr>
    <tr>
      <td>Second line</td>
    </tr>
    <tr>
      <td>Third line</td>
    </tr>
    <tr>
      <td>Fourth line</td>
    </tr>
    <tr>
      <td>Fifth line</td>
    </tr>
  </tbody>
</table>

CSS

table {
  border: 1px solid blue;
}

/* Selects the last three elements */
tr:nth-last-child(-n + 3) {
  background-color: pink;
}

/* Selects every element starting from the second to last item */
tr:nth-last-child(n + 2) {
  color: blue;
}

/* Select only the last second element */
tr:nth-last-child(2) {
  font-weight: 600;
}

结果

列表示例

数量查询

数量查询样式元素取决于它们的数量。在本例中,当给定列表中至少有三个列表项时,列表项变为红色。这是通过组合 nth-last-child 和通用兄弟选择器的功能来实现的

HTML

<h4>A list of four items (styled):</h4>
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ol>

<h4>A list of two items (unstyled):</h4>
<ol>
  <li>One</li>
  <li>Two</li>
</ol>

CSS

/* If there are at least three list items,
   style them all */
li:nth-last-child(n + 3),
li:nth-last-child(n + 3) ~ li {
  color: red;
}

结果

数量查询

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。