Appearance
CSS 伪类
伪类用来选择处于某种状态或某种位置的元素,而不是通过 class、id 等写死在 HTML 里。写法是选择器后加单冒号加伪类名,如 a:hover、li:first-child。
常见伪类分类
状态类(用户交互、链接等)
| 伪类 | 说明 |
|---|---|
:hover | 鼠标悬停时 |
:active | 鼠标按下未松开时 |
:focus | 获得焦点时(键盘/点击) |
:link | 未访问的链接 |
:visited | 已访问的链接 |
:disabled | 禁用状态(表单控件) |
:checked | 选中状态(单选/复选框) |
结构/位置类(在兄弟中的位置)
| 伪类 | 说明 |
|---|---|
:first-child | 父元素中的第一个子元素 |
:last-child | 父元素中的最后一个子元素 |
:nth-child(n) | 第 n 个子元素(可写 2n、2n+1、even、odd 等) |
:nth-last-child(n) | 从后数第 n 个 |
:first-of-type | 同类型中的第一个 |
:last-of-type | 同类型中的最后一个 |
:nth-of-type(n) | 同类型中的第 n 个 |
其它
| 伪类 | 说明 |
|---|---|
:not(选择器) | 不匹配该选择器的元素 |
:empty | 没有子元素的元素 |
常用示例
链接与按钮状态
css
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: darkblue; text-decoration: underline; }
a:active { color: red; }
button:hover { background: #eee; }
button:focus { outline: 2px solid blue; }
input:focus { border-color: blue; }列表奇偶行、首尾项
css
li:first-child { border-top: none; }
li:last-child { margin-bottom: 0; }
tr:nth-child(even) { background: #f9f9f9; }
tr:nth-child(odd) { background: white; }
/* 或 */
tr:nth-child(2n) { background: #f9f9f9; }:nth-child 的写法
- 数字:
:nth-child(3)第 3 个 - even / odd:偶数 / 奇数
- 公式:
:nth-child(2n+1)表示 1、3、5…(n 从 0 开始)
排除某些元素
css
p:not(.intro) {
text-indent: 2em;
}小结
- 伪类用单冒号,表示「某种状态或位置」。
- 常用::hover、:focus、:link、:visited、:active;结构上 :first-child、:last-child、:nth-child。
- :not(选择器) 用于排除;:disabled、:checked 用于表单状态。
下一节学习 CSS 伪元素:::before、::after 等。