此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

:nth-last-child

基线 广泛可用 *

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

* 此特性的某些部分的支持程度可能有所不同。

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

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

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

语法

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

关键字值

odd

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

even

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

函数符号

<An+B>

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

of <selector> 语法

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

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

备注:这与将选择器移到函数外部不同,例如:

css
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 开始,nn+1都会选择相同的元素。)

p:nth-last-child(1) or p:nth-last-child(0n+1)

表示所有处于兄弟节点中倒数第一位的元素<p>。这与:last-child选择器相同。

列表示例

HTML

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

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

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

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;
}

结果

规范

规范
Selectors Level 4
# nth-last-child-pseudo

浏览器兼容性

参见