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

1,262 阅读1分钟

下面是W3CSchool 中针对伪类选择器 :last-child 以及 :last-of-type的描述,如下

:last-child      p:last-child      选择属于其父元素最后一个子元素每个 <p> 元素。
:last-of-type    p:last-of-type    选择属于其父元素的最后 <p> 元素的每个 <p> 元素。

讲真的,怎么读都觉得是在是有些别扭 难懂

下面是我对这两者的理解:

  1. :last-child 先看下面的例子
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>last-child 和 last-of-type区别</title>
    <style type="text/css">
        .demo:last-child{
            color: blue;
        }
    </style>
</head>
<body>
    <div>
        <p class="demo">第一行</p>
        <p class="demo">第二行</p>
        <p class="demo">第三行</p> 
        <span>我是测试行</span>
    </div> 
</body>
</html>

这个的结果是

image.png

在看这个例子

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>last-child 和 last-of-type区别</title>
    <style type="text/css">
        .demo:last-child{
            color: blue;
        }
    </style>
</head>
<body>
    <div>
        <p class="demo">第一行</p>
        <p class="demo">第二行</p>
        <p class="demo">第三行</p> 
        <span class="demo">我是测试行</span>
    </div> 
</body>
</html>

这个的结果是

1638325780471.jpg

看完这两个例子应该理解:last-child的逻辑了--先在父级元素(div)中找到最后一个(span),之后看最后一个元素的类名是否和选择器类名(.demo)相同,如果相同就会赋予样式。

  1. :last-of-type 先看下面这个例子
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>last-child 和 last-of-type区别</title>
    <style type="text/css">
        .demo:last-of-type{
            color: blue;
        }
    </style>
</head>
<body>
    <div>
        <p class="demo">第一行</p>
        <p class="demo">第二行</p>
        <p class="demo">第三行</p> 
        <span class="demo">我是测试行</span>
    </div> 
</body>
</html>

先自己想一下会是什么结果 结果是这样的

1638325214104.jpg

看着结果是不是就明白了:last-of-type的逻辑--在父级元素(div)里先找到与类名(.dome)相匹配的节点类型(p和span),之后分别找到相同节点的最后一个元素,之后再将样式赋上去。

总结:经过上面的几个例子很清楚的就知道了两者的区别。:last-child就像w3c描述的一样他侧重的是最后一个元素,:last-of-type侧重的是与之选择器匹配的相同的类型。