CSS3 :nth-of-type() 选择器
:nth-of-type() 选择器允许您选择特定类型的元素,这些元素是其父元素中出现的第 N 个。它与 :nth-child() 选择器类似,但它只考虑特定类型的元素,而不是所有类型的元素。
语法
:nth-of-type(n)
其中:
n是一个整数,指定要选择的元素的顺序。
用法
:nth-of-type() 选择器可以用于各种目的,例如:
- 为特定类型的元素添加样式,无论它们在父元素中的位置如何。
- 为特定类型的元素添加交替样式。
- 选择父元素中最后或第一个特定类型的元素。
示例
为所有奇数个段落添加蓝色背景:
p:nth-of-type(odd) {
background-color: blue;
}为列表中的第一个和最后一个列表项添加红色边框:
li:nth-of-type(1), li:nth-of-type(last-child) {
border: 1px solid red;
}为父元素中最后一个 h2 元素添加下划线:
h2:nth-of-type(last-child) {
text-decoration: underline;
}兼容性
:nth-of-type() 选择器得到了所有现代浏览器的支持。
替代方案
在不支持 :nth-of-type() 选择器的浏览器中,您可以使用 :nth-child() 选择器来实现类似的效果。但是,您需要使用更复杂的表达式,因为 :nth-child() 选择器会考虑所有类型的元素。
例如,要为所有奇数个段落添加蓝色背景,您可以使用以下 :nth-child() 选择器:
p:nth-child(2n+1) {
background-color: blue;
}注意事项
:nth-of-type()选择器基于元素在父元素中的顺序,而不是在文档中的顺序。:nth-of-type()选择器不能用于选择根元素。:nth-of-type()选择器不能用于选择伪元素。