首页 > 编程笔记

CSS :first-child和:last-child伪类的用法

:first-child 伪类可以匹配第一个子元素,:last-child 伪类可以匹配最后一个子元素。

例如:
ol > :first-child {
   font-weight: bold;
   color: deepskyblue;
}
ol > :last-child {
   font-style: italic;
   color: red;
}
<ol>
   <li>内容</li>
   <li>内容</li>
   <li>内容</li>
</ol>
结果显示第一项内容表现为天蓝色加粗,最后一项内容表现为红色倾斜体,如下图所示。


图 1 :first-child和:last-child伪类的基本作用示意

虽然 :first-child 和 :last-child 伪类的含义首尾呼应,但这两个伪类并不是同时出现的。:first-child 出现得很早,自 IE7 浏览器就开始被支持了,而 :last-child 伪类是在 CSS3 时代出现的,自 IE9 浏览器才开始被支持。

因此,对于桌面端项目,在 :first-child 伪类和 :last-child 伪类都可以使用的情况下,优先使用 :first-child 伪类。例如,若想列表上下都有 20px 的间距,则下面两种实现都是可以的:
li {
   margin-top: 20px;
}
li:first-child {
   margin-top: 0;
}
li {
   margin-bottom: 20px;
}
li:last-child {
   margin-top: 0;
}
建议优先使用第一种写法。如果项目不需要兼容 IE8 浏览器,不推荐使用第二种写法,而建议使用 :not 伪类,如:
li:not(:last-child) {
   margin-bottom: 20px;
}

推荐阅读