在CSS中,选择器可以帮助你精确选择特定的元素。以下是你提到的各种选择器的解释:
1. 第一个元素
- 选择器:
:first-child
- 用法: 选择属于其父元素的第一个子元素。
- 示例:
p:first-child { color: red; }
2. 最后一个元素
- 选择器:
:last-child
- 用法: 选择属于其父元素的最后一个子元素。
- 示例:
p:last-child { color: blue; }
3. 单数和双数元素
- 选择器:
:nth-child(odd)
和:nth-child(even)
- 用法:
:nth-child(odd)
: 选择所有奇数位置的子元素(1, 3, 5…)。:nth-child(even)
: 选择所有偶数位置的子元素(2, 4, 6…)。
- 示例:
li:nth-child(odd) { background-color: lightgray; } li:nth-child(even) { background-color: white; }
4. 第N个元素
- 选择器:
:nth-child(n)
- 用法: 选择属于其父元素的第N个子元素,N可以是数字或表达式(如
2n
、3n+1
等)。 - 示例:
li:nth-child(3) { font-weight: bold; } li:nth-child(2n) { background-color: yellow; }
5. 反选
- 选择器:
:not(selector)
- 用法: 选择不匹配特定选择器的元素。
- 示例:
div:not(.active) { opacity: 0.5; }
6. nth-child 和 last-child,first-child
这些选择器已经在前面提到,分别用于选择第一个、最后一个和特定位置的子元素。
例子总结
结合这些选择器,你可以灵活地为网页中的元素添加样式。确保在HTML结构中使用这些选择器时,理解它们的行为,以便达到预期效果。