CSS3伪类选择器last-of-type的坑

132 阅读1分钟

先来看下last-of-type的描述

last-of-type: 选择器匹配属于其父元素的特定类型的最后一个子元素的每个元素。

接下来上代码

<!DOCTYPE html>
    <html>
        <head>
            <style> 
                .nth {
                  display: block;
                  width: 100%;
                  height: 30px;
                  margin: 0 0 10px 0;
                  background-color: red;
                }
                .nth:last-of-type {
                  background-color: yellow;
                }
            </style>
        </head>
        <body>
            <div class="nth"></div>
            <p class="nth"></p>
            <p class="nth"></p>
            <span class="nth"></span>
            <span class="nth"></span>
            <div class="nth"></div>
        </body>
    </html>

预期效果:最后一个类名为nth的元素背景颜色为黄色,实际上并不是。。。

下面来看下实际效果图:

image.png

发现类名为nth的每种标签的最后一个元素背景颜色全变成黄色

结论:last-of-type通过类名匹配的时候,会匹配包含该类名的所有不同标签的最后一个元素