使用 :last-child 可选中父元素下最后一个子元素,如 li:last-child 去除列表末项边框;若需选中特定类型最后一个元素,则用 :last-of-type,例如 p:last-of-type 给最后一段文字加样式。

要选中最后一个子元素,可以使用 CSS 中的 :last-child 伪类选择器。这个选择器能匹配父元素下最后一个同级子元素。
使用 :last-child 选择最后一个子元素
当你想选中某个容器内的最后一个子元素时,直接在选择器后加上 :last-child 即可。
例如,选中列表中最后一个 li 元素:li:last-child {
background-color: #f0f0f0;
}
如果只想要特定类型的最后一个子元素
有时候你希望选中某一类型元素中的最后一个,比如多个 p 标签中的最后一个。这时可以用 :last-of-type。
示例:选中父元素内最后一个 p 元素p:last-of-type {
color: red;
}
与 :last-child 不同,:last-of-type 不要求该元素是父元素的最后一个子节点,只要它是该标签类型的最后一个即可。
立即学习“前端免费学习笔记(深入)”;
实际应用场景
- 去除列表最后一个项的下边框:li:last-child { border-bottom: none; }
- 为最后一段文字添加特殊样式
- 在卡片布局中调整最后一个卡片的外边距
基本上就这些。根据结构选择 :last-child 或 :last-of-type,就能准确选中目标元素。不复杂但容易忽略细节。










