first-child、first-of-type、nth-child和nth-of-type的区别

公共样式
span,label{
	display: inline-block;
	width: 80px;
	line-height: 30px;
	border: 1px solid #000000
}

1、first-child匹配第一个子元素

匹配第一个span且是第一个子元素
.test1 span:first-child{
	background-color: #FFA500;
}
<div class="test1">
    <span>111</span>
    <span class="s1">222</span>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span>555</span>
</div>

在这里插入图片描述

错误示范(不是第一个子元素)
.test2 .s1:first-child{
	background-color: #FFA500;
}
<div class="test2">
    <span>111</span>
    <span class="s1">222</span>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span>555</span>
</div>

在这里插入图片描述

因为第一个子元素span没有.s1,所有匹配不到

2、first-of-type匹配相同类型子元素的第一个

匹配第一个label / span类型且是类型中的第一个元素
.test3 .s1:first-of-type{
	background-color: #FFA500;
}
<div class="test3">
    <label class="s1">111</label>
    <label class="s1">222</label>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span class="s1">555</span>
</div>

在这里插入图片描述

.s1可以匹配两种类型,两个label和3个span,这两种类型的第一个都将被匹配到

错误示范
.test4 .s1:first-of-type{
	background-color: #FFA500;
}
<div class="test4">
    <span>111</span>
    <span class="s1">222</span>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span>555</span>
</div>

在这里插入图片描述

.s1匹配到3个span,但是它们的位置不在第一个,所以匹配不到

3、nth-child(n)匹配第n个子元素,序号从1开始,nth-child(1)等同于first-child

匹配第2个元素
.test5 .s1:nth-child(2){
	background-color: #FFA500;
}
<div class="test5">
    <span>111</span>
    <span class="s1">222</span>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span>555</span>
</div>

在这里插入图片描述

错误示范
.test6 .s1:nth-child(1){
	background-color: #FFA500;
}
<div class="test6">
    <span>111</span>
    <span class="s1">222</span>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span>555</span>
</div>

在这里插入图片描述

匹配到3个子元素,但是它们没有在1号位置的

4、nth-of-type(n)匹配相同类型的子元素的第n个,序号从1开始,nth-of-type(1)等同于first-of-type

.test7 .s1:nth-of-type(2){
	background-color: #FFA500;
}
<div class="test7">
    <label class="s1">111</label>
    <label class="s1">222</label>
    <span class="s1">333</span>
    <span class="s1">444</span>
    <span class="s1">555</span>
</div>

在这里插入图片描述

总结

first-child和nth-child匹配的是子元素的第几个

first-of-type和nth-of-type匹配的是某种类型的第几个

同样的还有last-child、nth-last-child、last-of-type、 nth-last-of-type(n)

以及only-of-type(子元素中同类型元素只有一个)和only-child(只有一个子元素)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值