0%

CSS last-child vs last-of-type

:last-child

:last-child是一个CSS伪类,它表示一组元素中的最后一个。

:last-of-type

:last-of-type也是一个CSS伪类,它表示一组同类元素中的最后一个。注意这里多了一个限制:同类

那么这两者有什么区别呢?我们来看一个例子。
给定如下html代码,现在要求你写一段CSS,设置最后一个li元素的背景颜色为绿色。

1
2
3
4
5
<ul>
<li>Angular</li>
<li>React</li>
<li>Vue</li>
</ul>

以下两种写法都可以实现这个要求。

1
2
3
li:last-child {
background-color: green;
}
1
2
3
li:last-of-type {
background-color: green;
}

现在我们稍稍改动一下html代码,增加一个span元素作为最后一个子元素。

1
2
3
4
5
6
<ul>
<li>Angular</li>
<li>React</li>
<li>Vue</li>
<span>JavaScript</span>
</ul>

这时候下面的方法就不好使了,为什么呢?实际上li:last-child不会选中任何元素,因为span是这组元素的最后一个元素,所以要选中这组元素的最后一个li元素是找不到的。如果改成span: last-child,那么就可以选中span元素了。

1
2
3
li:last-child {
background-color: green;
}

但是下面这种方法仍然好用,因为我们指定了type为li,所以它会选中最后一个li元素。

1
2
3
li:last-of-type {
background-color: green;
}

参考