CSS :last-of-type 详解 | AI生成和翻译

Home 2026.02

问题: CSS 中的 :last-of-type 是什么意思?

答案:

CSS 中的 :last-of-type 伪类选择同一父元素内其同胞元素中最后一种类型的元素(其标签名)。

关键特性

视觉示例

<div class="container">
  <p>First paragraph</p>
  <p>Second paragraph</p>
  <div>Some div</div>
  <p>Last paragraph</p>     ← this one is selected by p:last-of-type
  <div>Another div</div>
</div>
p:last-of-type {
  color: red;
  font-weight: bold;
}

→ 只有“Last paragraph”变为红色 + 粗体

更常见的真实世界示例

/* Last <li> in any <ul> or <ol> */
li:last-of-type {
  border-bottom: none;
}

/* Last article inside a section (very common pattern) */
article:last-of-type {
  margin-bottom: 0;
}

/* Last <td> in every table row */
tr td:last-of-type {
  text-align: right;
}

/* Last <p> inside an .entry-content (blog post style) */
.entry-content p:last-of-type {
  margin-bottom: 1.8em;
}

:last-of-type 与 :last-child 的区别——重要差异

选择器 选择最后一个子元素…… 是否关心标签名? 示例中被选中的元素
:last-child …无论其标签名是什么 父元素中的最后一个元素
:last-of-type …但仅限于其自身标签类型的最后一个 同胞元素中该特定标签的最后一个元素
<section>
  <h2>Title</h2>
  <p>Text</p>
  <p>Text</p>           ← p:last-of-type 选择这个
  <div>Footer</div>     ← div:last-of-type 选择这个
                         :last-child 会选择这个 div
</section>

总结——何时使用 :last-of-type

当你想针对容器内特定元素类型的最后一次出现时使用它,特别是当:

参考资料:


Back Donate