CSS3伪类选择器nth-child和nth-of-type浅析

本文介绍了CSS3中的nth-child和nth-of-type伪类选择器,详细阐述了它们的定义、用法及区别。 nth-child(n)选择器匹配父元素的第n个子元素,不考虑元素类型,而nth-of-type(n)则限制为特定类型的第n个子元素。此外,文章还提到了关键字even和odd以及公式在选择器中的应用。

1. nth-child

定义和用法
:nth-child(n) 选择器匹配属于其父元素的第 n 个子元素,不论元素的类型。n 可以是数字、关键词或公式。


① n为数字时,n为大于0的整数

.box :nth-child(1){background-color: red;}
<div class="box">
    <div>1-1</div>  
    <div>2-2</div>
</div>

这里写图片描述


② n为关键字,even(偶数,等价于2n)、odd(奇数,等价于2n+1)

.box :nth-child(odd){background-color: red;}
.box :nth-child(even){background-color: green;}

这里写图片描述


③ n为公式
例如:,n+4(大于等于4),-n+5(小于等于5),3n+1(隔二取一)等

.box :nth-child(n+4){background-color: red;}
.box :nth-child(-n+2){background-color: green;}

这里写图片描述


④ 其他, nth-last-child倒数第几个

.box :nth-last-child(3){background-color: green;}

这里写图片描述


2. nth-of-type

定义和用法
:nth-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素的每个元素。n 可以是数字、关键词或公式。

nth-of-type(n)和nth-child(n)的用法类似,不过nth-of-type(n)必须指定子元素的标签类型


nth-child与nth-of-type的区别
nth-child(n)是子元素的第n个,tagName:nth-of-type(n)子元素中标签名为tagName的第n个。

.box p:nth-of-type(1){background-color: red;}
.box div:nth-of-type(2){background-color:green;}
.box div:nth-child(2){background-color:yellow;}
<div class="box">
    <p>我是第一个段落</p>
    <div>1-1</div>  
    <div>2-2</div>
</div>

这里写图片描述


3. 小结

选择器数字关键字公式
nth-child大于0的整数even(2n), odd(2n+1)3n+1,4+n,-n+2
nth-last-child大于0的整数
nth-of-type大于0的整数even(2n), odd(2n+1)3n+1,4+n,-n+2
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值