nth-of-type的属性和用法
一、先来介绍一下nth-child(n)的弊端:
我们可以先给一个div盒子,然后里面放上一些行内元素作为研究对象。代码如下:

<div>
        <p>你好</p>
        <span>我是1span</span>
        <span>我是2span</span>
        <span>我是3span</span>
</div>

先来介绍一下nth-child(n)的弊端:nth-child(n) 在选取的时候是不会限定类型的,不管里面的子元素是否同一类型只会按照所给范围里面所有子选项的顺序来进行选择,例如:

div :nth-child(1) {
        background-color: pink;
    }
div :nth-child(2) {
        background-color: seagreen;
    }

以上用nth-child(n)来进行选择第一个和第二个的时候,在div盒子里面有两种类型的行内元素,但是nth-child(n)是不受类型影响的,结果会选择到<p>你好</p><span>我是1span</span>这两个,将<p>你好</p>所代表的元素显示成pink颜色,将<span>我是1span</span>所代表的元素显示成seagreen颜色。

那么这里我们如果用nth-child(n)来选取div中满足<span>类型的元素呢?代码举例如下:

div span :nth-child(1) {        
        background-color: tan;
       }

事实证明这种情况是选取不出来的,因为nth-child()在选取的时候是不限定类型的, 那么此处在选取的时候,本来是按照div里面的第一个来选取的,而div里面的第一个并不是span类型,所以无法选取。(敲黑板:这里nth-child()遇到的无法选取的情况,nth-of-type可以很好的解决,具体如下介绍)
二、介绍nth-of-type的属性、用法和优点:
我们还是先给一个div盒子,然后里面放上一些行内元素作为研究对象。代码如下:

<div>
        <p>你好</p>
        <span>我是1span</span>
        <span>我是2span</span>
        <span>我是3span</span>
</div>

nth-of-type可以选择指定类型的元素,很好的解决了nth-child()在上面遇到的问题 ,举例如下

div span:first-of-type {
        background-color: chartreuse;
    }
    
div span:last-of-type {
        background-color: darkblue;
    }   

这里我们直接用nth-of-type来选取div中满足<span>类型的元素。以上选取方法是直接在div中选取满足span类型的第一个和最后一个元素,将first(第一个)的颜色变成chartreuse,将last(最后一个)的颜色变成darkblue颜色。

备注:nth-of-type(n)的具体用法类似于nth-child(n)的用法(公式也可用),例如:

 div span:nth-of-type(2) {
        background-color: darkred;
    }

就可以用来选择span类型里面的第二个。

知识点补充:
像以下这种情况,<ul>里面只有<li>这一种子元素,此时用nth-child()nth-of-type效果等价

<ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐