css 结构伪类选择器:first-child last-child nth-child(n) nth-last-child(n) only-child first-of-type last-of-type nth-of-type(n) nth-last-of-type(n) empty

发布时间:2025-05-09      访问量:25
CSS 中的结构伪类选择器是一种强大的工具,它允许你基于元素在文档树中的位置或结构关系来选择元素。以下是一些常用的结构伪类选择器及其用法:

1. **`:first-child`**
选择作为其父元素的第一个子元素的元素。

css li:first-child { color: red; /* 选择每个ul/ol中的第一个li */ }

2. **`:last-child`**
选择作为其父元素的最后一个子元素的元素。

css li:last-child { color: blue; /* 选择每个ul/ol中的最后一个li */ }

3. **`:nth-child(n)`**
选择作为其父元素的第 `n` 个子元素的元素,`n` 可以是数字、关键词(如 `odd` 或 `even`)或公式(如 `2n+1`)。

css /* 选择每个ul中的奇数位置的li */ li:nth-child(odd) { background-color: lightgray; } /* 选择每个ul中的前3个li */ li:nth-child(-n+3) { font-weight: bold; }

4. **`:nth-last-child(n)`**
与 `:nth-child` 类似,但从最后一个子元素开始计数。

css /* 选择每个ul中的倒数第2个li */ li:nth-last-child(2) { text-decoration: underline; }

5. **`:only-child`**
选择作为其父元素的唯一子元素的元素。

css p:only-child { font-size: 1.2em; /* 只选择没有兄弟元素的p */ }

6. **`:first-of-type`**
选择作为其父元素下特定类型的第一个子元素的元素。

css p:first-of-type { margin-top: 0; /* 选择每个容器中的第一个p */ }

7. **`:last-of-type`**
选择作为其父元素下特定类型的最后一个子元素的元素。

css p:last-of-type { margin-bottom: 0; /* 选择每个容器中的最后一个p */ }


8. **`:nth-of-type(n)`**
选择作为其父元素下特定类型的第 `n` 个子元素的元素。

css /* 选择每个容器中的偶数位置的p */ p:nth-of-type(even) { color: green; }

9. **`:nth-last-of-type(n)`**
与 `:nth-of-type` 类似,但从最后一个子元素开始计数。

css /* 选择每个容器中的倒数第1个img */ img:nth-last-of-type(1) { border: 2px solid red; }

10. **`:only-of-type`**
选择作为其父元素下特定类型的唯一子元素的元素。

css span:only-of-type { display: block; /* 只选择没有其他span兄弟的span */ }

11. **`:empty`**
选择没有子元素(包括文本节点)的元素。

css p:empty { display: none; /* 隐藏空的p元素 */ }

示例用法
假设 HTML 结构如下:
html <div class="container"> <p>第一个段落</p> <p>第二个段落</p> <div>一个div</div> <p>第三个段落</p> </div>

以下 CSS 规则将:
css .container p:first-child { color: red; /* 不选择任何元素(第一个子元素是div) */ } .container p:first-of-type { font-weight: bold; /* 选择第一个p */ } .container p:nth-of-type(2) { background: yellow; /* 选择第二个p */ }

注意事项
- **`:nth-child` vs `:nth-of-type`**:
- `:nth-child` 考虑所有子元素的位置。
- `:nth-of-type` 只考虑同类型元素的位置。

- **公式规则**:
- `2n` 或 `even`:偶数位置。
- `2n+1` 或 `odd`:奇数位置。
- `n+3`:从第3个开始的所有元素。
- `-n+3`:前3个元素。

结构伪类选择器在创建响应式设计、表格样式和列表布局时特别有用,可以减少对额外类名的依赖。
堆内存
多线程
strdup
初始化器
冒泡排序
增删改查
BufferedReader
输入输出
面向对象
生命周期
闭包的概念
原型链
Flask
mysql-connector-python
单例模式
浅拷贝
隔离级别
索引
InnoDB
左连接
聚合函数
PuTTY
TRUNCATE
str_starts_with_many
DateTime
array_combine
闭包的概念