CSS 参考手册 目录

CSS3 :nth-last-child() 选择器

概述

:nth-last-child() CSS3 选择器用于选择元素列表中的从最后一个元素开始倒数的特定位置的子元素。它与 :nth-child() 选择器类似,但从最后一个元素开始计数。

语法

------------------

其中:

  • n:要选择的子元素的位置,从最后一个元素开始倒数。

用法

:nth-last-child() 选择器可以用来选择:

  • 最后一个子元素:li:nth-last-child(1)
  • 倒数第二个子元素:li:nth-last-child(2)
  • 倒数第三个子元素:li:nth-last-child(3)
  • 等等

示例

HTML 代码:

----
  ------ ------
  ------ ------
  ------ ------
  ------ ------
  ------ ------
-----

CSS 代码:

-- --------- --
-------------------- -
  ----------------- ----
-

-- ---------- --
-------------------- -
  ----------------- -----
-

结果:

  • 最后一个子元素(“项目 5”)将具有红色背景。
  • 倒数第二个子元素(“项目 4”)将具有蓝色背景。

负值

:nth-last-child() 选择器也可以使用负值,从倒数第一个元素开始计数。

语法:

-------------------

其中:

  • n:要选择的子元素的位置,从倒数第一个元素开始计数。

示例

HTML 代码:

----
  ------ ------
  ------ ------
  ------ ------
  ------ ------
  ------ ------
-----

CSS 代码:

-- ---------- --
--------------------- -
  ----------------- ------
-

-- ---------- --
--------------------- -
  ----------------- -------
-

结果:

  • 倒数第一个子元素(“项目 5”)将具有绿色背景。
  • 倒数第二个子元素(“项目 4”)将具有黄色背景。

与 :last-child() 选择器的关系

:nth-last-child(1) 选择器与 :last-child 选择器等效,后者选择列表中的最后一个子元素。

浏览器支持

:nth-last-child() 选择器在所有现代浏览器中都得到广泛支持。

其他注意事项

  • :nth-last-child() 选择器可以与其他选择器组合使用。
  • :nth-last-child() 选择器不会影响元素的文档顺序。
  • :nth-last-child() 选择器不能用于选择根元素。

下一篇:CSS 参考手册