:nth[-last]-child(n) 与 :nth[-last]-of-type(n) 的区别

1,042 阅读3分钟

为了能搞清楚 :nth[-last]-child 和 :nth[-last]-of-type,我们先来弄清楚 :first-child:last-child:first-of-type:last-of-type 的区别。你可能会问:为什么呢?我的回答是:后面 4 个伪类是前面 4 个的具体形式。

具体为:

  • :first-child 等同于 :nth-child(1)
  • :last-child 等同于 :nth-last-child(1)
  • :first-of-type 等同于 :nth-of-type(1)
  • :last-of-type 等同于 :nth-last-of-type(1)

咱们以小见大,就能知道 :nth[-last]-child:nth[-last]-of-type 的区别了。

以下面的 HTML 结构为例:

<nav class="crumbs">
    <div>
        <span class="crumb is-active">Jump Bike 3000</span>
        <a class="crumb" href="javascript:">Bikes</a>
        <a class="crumb" href="javascript:">BMX</a>        
    </div>
</nav>

<style>
.crumb {
    font-size: 1.5rem;
    
    &.is-active {
    	color: deeppink;
    }
}
</style>

呈现效果如下:

image.png

:first-child

添加样式 .crumb:first-child(等同于 .crumb:nth-child(1)):

.crumb:first-child {
	background-color: pink;
}

效果:

image.png

.crumbs 中包含 3 个 .crumb,第一个 .crumb 背景变粉红。

:last-child

添加样式 .crumb:last-child(效果等同于 .crumb:nth-last-child(1)):

.crumb:last-child {
	background-color: skyblue;
}

效果:

image.png

最后一个 .crumb 背景变天蓝色。

:first-of-type

添加样式 .crumb:first-of-child(等同于 .crumb:nth-of-type(1)):

.crumb:first-of-type {
	background-color: pink;
}

效果:

image.png

发现有两处背景变粉红色的 .crumb!原因在于,:nth-of-type 是区分类型的。

我们再来看一遍 HTML 结构:

<nav class="crumbs">
    <div>
		    <span class="crumb is-active">Jump Bike 3000</span>
        <a class="crumb" href="javascript:">Bikes</a>
        <a class="crumb" href="javascript:">BMX</a>        
    </div>
</nav>

背景发生变化的是头两个:span.crumb 和 a.crumb。可以如此理解——在 <div> 中:

  • 第一个 .crumb 对应的标签类型是 <span>,它是 <span> 里的第一个(也是唯一一个) .crumb,因此命中了。
  • 第二个 .crumb 对应的标签类型是 <a>,它是 <a> 里的第一个 .crumb(下面还有一个 <a class="crumb">),因此也被命中了。

:last-of-type

添加样式 .crumb:last-of-type(效果等同于 .crumb:nth-last-of-type(1) ):

.crumb:last-of-type {
	background-color: skyblue;
}

效果:

image.png

发现也有两处背景变色了。分别是第一个 .crumb 和第三个(也是最后一个) .crumb

同理,我们也来分析一下:

  • 第一个 .crumb 对应的标签类型是 <span>,这个 <span> 既是 <div> 中同类型标签的第一个 .crumb也是最后一个 .crumb,因此被命中了。
  • 第三个 .crumb 对应的标签类型是 <a>,它是 <a> 里的第二个也是最后一个 .crumb,因此也被命中了。

总结

  • xx:nth[-last]-child(n) 含义是:匹配 xx 元素,且是正数(或倒数)第 n 个的。
  • xx:nth[-last]-of-type(n) 含义是:匹配同类型标签中正数(或倒数)第 n 个,且是 xx 的元素。

demo 地址:codepen.io/zhangbao/pe…

(正文完)


广告时间(长期有效)

我有一位好朋友开了一间猫舍,在此帮她宣传一下。现在猫舍里养的都是布偶猫。如果你也是个爱猫人士并且有需要的话,不妨扫一扫她的【闲鱼】二维码。不买也不要紧,看看也行。

(完)