简介
:nth-child() 是一个强大的 CSS3 选择器,用于选择父元素中特定位置的子元素。它基于子元素在父元素中的位置,从 1 开始计数。
语法
:nth-child(n)
其中:
n是一个整数,表示要选择的子元素在父元素中的位置。
参数
:nth-child() 选择器接受以下参数:
- n:一个整数,表示要选择的子元素在父元素中的位置。
- even:选择所有偶数位置的子元素。
- odd:选择所有奇数位置的子元素。
- of type:选择特定类型的子元素。例如,
:nth-child(2 of type p)将选择父元素中的第二个p元素。
示例
选择父元素中的第一个子元素:
:nth-child(1) {
color: red;
}选择父元素中的最后一个子元素:
:nth-child(last-child) {
background-color: blue;
}选择父元素中所有偶数位置的子元素:
:nth-child(even) {
border: 1px solid green;
}选择父元素中所有奇数位置的子元素:
:nth-child(odd) {
border: 1px solid orange;
}选择父元素中的所有 p 元素的第二个子元素:
:nth-child(2 of type p) {
font-weight: bold;
}高级用法
:nth-child() 选择器可以与其他选择器组合使用以实现更复杂的选择。例如:
选择父元素中的奇数位置的 li 元素:
ul li:nth-child(odd) {
background-color: lightgray;
}选择父元素中除第一个子元素之外的所有子元素:
:not(:first-child) {
padding: 10px;
}浏览器支持
:nth-child() 选择器在所有现代浏览器中都得到广泛支持。
| 浏览器 | 支持 |
|---|---|
| Chrome | 是 |
| Firefox | 是 |
| Safari | 是 |
| Edge | 是 |
| Internet Explorer | 9+ |
注意事项
:nth-child()选择器基于元素的文档顺序,而不是显示顺序。- 隐藏的元素仍然会被
:nth-child()选择器计数。 - 对于具有动态内容的页面,
:nth-child()选择器可能会产生意外的结果。 - 使用
:nth-child()选择器时要小心,因为它可能会导致性能问题。