在css中选择last-of-type元素方法

19次阅读

使用 :last-of-type 伪类 可选择父元素中同类型标签的最后一个元素,例如 p:last-of-type 会选中最后一个段落标签,即使其后存在其他类型元素;在给定 html 中,p:last-of-type 将“段落 3”设为红色,因其是所有 p 元素的最后一个;与 :last-child 不同,后者要求元素必须是父级的最后一个子节点且不区分类型,而 :nth-last-of-type(1) 则等效于 :last-of-type。

在 css 中选择 last-of-type 元素方法

css 中选择最后一个特定类型的元素,可以使用 :last-of-type 伪类。它会选中父元素中同类型标签的最后一个元素。

基本语法

:last-of-type 根据元素的类型(即标签名)来匹配其在父容器中的最后一个实例。例如:

  • p:last-of-type 会选择其父元素中最后一个 <p> 元素。
  • li:last-of-type 会选择列表中最后一个 <li> 元素(即使后面还有其他类型的元素)。

实际示例

假设有如下 HTML 结构:

<div>   <p> 段落 1 </p>   <p> 段落 2 </p>   <span> 文字内容 </span>   <p> 段落 3 </p> </div>

使用以下 CSS:

立即学习 前端免费学习笔记(深入)”;

在 css 中选择 last-of-type 元素方法

腾讯元宝

腾讯混元平台推出的 AI 助手

在 css 中选择 last-of-type 元素方法223

查看详情 在 css 中选择 last-of-type 元素方法

p:last-of-type {color: red; }

结果是“段落 3”变成红色,因为它是所有 p 标签中的最后一个。

与其他伪类的 区别

:last-of-type 是按元素类型选择最后一个,不同于:

  • :last-child:必须是父元素的最后一个子元素,且是唯一一个类型无关的“末尾”元素。
  • :nth-last-of-type(n):更灵活的方式,比如 :nth-last-of-type(1) 等同于 :last-of-type

基本上就这些。使用 :last-of-type 能精准定位某类标签的末位元素,不依赖其是否为最后一个子节点,很实用。

以上就是在

站长
版权声明:本站原创文章,由 站长 2025-10-29发表,共计786字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
1a44ec70fbfb7ca70432d56d3e5ef742
text=ZqhQzanResources