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

1万+

被折叠的 条评论
为什么被折叠?



