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

使用 :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 能精准定位某类标签的末位元素,不依赖其是否为最后一个子节点,很实用。

以上就是在

上一篇
下一篇
text=ZqhQzanResources