:last-child 与: last-of-type 的区别

5,715
原文链接: jcwblog.com

在做列表的时候,会经常遇到最后一个元素与其他元素在样式上会有差异的情况。

如果是单纯的静态页面,可以使用class去控制。也可以在页面渲染结束之后,使用js去控制。若对于兼容性的要求并非那么严格,可以使用css去控制。个人建议使用css控制。

然而,就在这种情况下,我遇到了一个问题,就是:last-child:last-of-type经常搞混,不知什么情况下使用哪个。

为了解决这个一直困扰我的问题,我查了一下CSS手册。

:last-child

关于:last-child手册中是这么解释的:

The :last-child CSS pseudo-class represents the last element among a group of sibling elements.

CSS伪类:last-child代表在一群兄弟元素中的最后一个元素。

举个栗子:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
        li {
            border-bottom: 1px solid #AAAAAA;
        }
        li:last-child {
            border-bottom-color: #F00;
        }
    </style>
</head>
<body>
    <ul>
        <li>我是第1个li元素的内容</li>
        <li>我是第2个li元素的内容</li>
        <li>我是第3个li元素的内容</li>
        <li>我是最后一个li元素的内容</li>
    </ul>
</body>
</html>

:last-child代码运行图

从代码和图可以看出:last-child选择了最后一个li标签。

同时,我们换另外一段代码,看看是否还有这样的效果。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
        p {
            border-bottom: 1px solid #AAAAAA;
        }
        p:last-child {
            border-bottom-color: #F00;
        }
    </style>
</head>
<body>
    <p>我是第1个p元素的内容</p>
    <p>我是第2个p元素的内容</p>
    <p>我是第3个p元素的内容</p>
    <p>我是最后一个p元素的内容</p>
    <div>我是个干扰元素</div>
</body>
</html>

:last-child代码运行图

从代码和图可以看出,:last-child并没有起到我们想要的作用。如果,这个时候去掉最后的div标签,再看看效果。

:last-child代码运行图

这时,效果出来了,那么,可以总结了。

:last-child表示其父元素的最后一个子元素,且这个元素是css指定的元素,才可以生效。

:last-of-type

关于:last-of-type手册中是这么解释的:

The :last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.

CSS伪类:last-of-type代表在一群兄弟元素中的最后一个指定类型的元素。

直接用上面两个栗子。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
        p {
            border-bottom: 1px solid #AAAAAA;
        }
        p:last-of-type {
            border-bottom-color: #F00;
        }
    </style>
</head>
<body>
    <p>我是第1个p元素的内容</p>
    <p>我是第2个p元素的内容</p>
    <p>我是第3个p元素的内容</p>
    <p>我是最后一个p元素的内容</p>
</body>
</html>

:last-of-type代码运行图

没有干扰元素,OK。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
        p {
            border-bottom: 1px solid #AAAAAA;
        }
        p:last-of-type {
            border-bottom-color: #F00;
        }
    </style>
</head>
<body>
    <p>我是第1个p元素的内容</p>
    <p>我是第2个p元素的内容</p>
    <p>我是第3个p元素的内容</p>
    <p>我是最后一个p元素的内容</p>
    <div>我是干扰元素</div>
</body>
</html>

:last-of-type代码运行图

有干扰元素,OK。

:last-of-type表示其父元素下的最后一个指定类型的元素

结尾

总结了一番,对于什么场景下使用:last-child:last-of-type又了相应的认识,以后犯错的可能性就会降低了很多。

原创文章,转载请注明出处