:nth-child(n)和:nth-of-type(n)

284 阅读2分钟

微信图片_20210420153233.png

我们通常不会在标签后面,而是 .class后加上这类选择器,但是有时候无法得到我们想要的效果。

.class:nth-child(n)  会直接在 .class 的父元素中找,如果第n个子元素是 .class 属性,则匹配成功。

.class:nth-of-type(n)  会先判断 .class 是什么标签,再在父元素中查找该标签,如果第n个该标签的元素是 .class 属性,则匹配成功。

<body>
    <div class="wrap" style="display:flex;flex-direction:column;">
        <h4 class="item1">test</h4>
        <span class="item1">第一个span<span>-----第一个span的子span</span></span>
        <span class=``"item2"``>第二个span</span>
        <span class=``"item2"``>第三个span</span>
    </div>
</body>

例一、

div:nth-child(1){
    color#ff9900;
}

这个比较好理解,div的父元素是body,body第一个子元素,如果是div,则匹配

微信图片_20210420162621.png

例二、

span:nth-child(1){
    color#ff9900;
}

这里第一个span没有变色,是因为span的父元素div的第一个子元素不是span而是h4,无法匹配。

微信图片_20210420162934.png

例三、

span:nth-of-type(1) {
    color:red;
}

如果你希望wrap第一个span变色,需要使用  :nth-of-type,它只会计算该类型的元素。span的父元素div中所有的span子元素中的第一个匹配。

微信图片_20210420164631.png

例四、

.item1:nth-child(1) {
    color#ff9900;
}

如果使用  .class,上面写法会匹配 .item 父元素div中的第一个元素。

微信图片_20210420165407.png

例五、

.item1:nth-of-type(1) {
    color:red;
}

先查找item1所属标签 是h4和span,再匹配父元素div中第一个h4,和第一个span,都是 .item1。

微信图片_20210420172230.png

例六、

.item1:nth-of-type(2) {
    color:red;
}

先查找item1所属标签 h4和span,再查找父元素div中第二个h4,和第二个span,h4没有第二个,第二个span不是 item1,都无法匹配

微信图片_20210420165121.png

例七、

.item2:nth-of-type(2) {
    color:red;
}

先查找item2所属标签为span,再查找父元素div中第二个span,检查它是不是 item2,是则匹配成功。但是和我们想象中不一样,我们更希望是第二个item2,也就是第三个item为红色。

微信图片_20210420205315.png