CSS 伪类(Pseudo-classes)
在 CSS 中,伪类(Pseudo-classes) 是一种用于选中元素特定状态的选择器,不需要为元素额外添加 class 或 id,就能在特定交互或结构条件下应用样式。
✅ 一、伪类是什么?
伪类以冒号 :
开头,不会直接在 HTML 中出现,它表示“元素处于某种状态”或“满足某种条件”。
a:hover {
color: red;
}
上面这段表示:鼠标悬停时,链接字体变红。
✅ 二、常用交互伪类(用户操作相关)
伪类 | 说明 | 示例 |
---|---|---|
:hover | 鼠标悬停在元素上 | button:hover |
:active | 鼠标点击元素时(按下未松开) | a:active |
:focus | 元素获得焦点时(如输入框) | input:focus |
:visited | 链接已访问过时 | a:visited |
:link | 尚未访问的链接 | a:link |
:focus-visible | 仅键盘导航时显示焦点 | button:focus-visible |
🔔 注意: :hover
和 :active
通常用于交互设计,注意顺序(CSS 中顺序 matters):
a:link,
a:visited,
a:hover,
a:active {
/* 顺序不能乱! */
}
✅ 三、结构伪类(基于元素在文档中的位置)
伪类 | 说明 | 示例 |
---|---|---|
:first-child | 第一个子元素 | ul li:first-child |
:last-child | 最后一个子元素 | div p:last-child |
:nth-child(n) | 第 n 个子元素(从 1 开始) | li:nth-child(2) |
:nth-last-child(n) | 倒数第 n 个子元素 | tr:nth-last-child(1) |
:only-child | 唯一的子元素 | div p:only-child |
:first-of-type | 同类型中第一个元素 | p:first-of-type |
:last-of-type | 同类型中最后一个元素 | span:last-of-type |
:nth-of-type(n) | 同类型中第 n 个元素 | li:nth-of-type(2) |
💡 :nth-child()
还可以用公式:
odd
表示奇数(1, 3, 5…)even
表示偶数(2, 4, 6…)2n + 1
表示奇数,3n
表示 3 的倍数元素
li:nth-child(odd) {
background-color: #f0f0f0;
}
✅ 四、状态伪类(表单元素)
伪类 | 说明 | 示例 |
---|---|---|
:checked | 被选中(如复选框、单选按钮) | input[type=checkbox]:checked |
:disabled | 被禁用 | input:disabled |
:enabled | 可用状态 | button:enabled |
:required | 必填字段 | input:required |
:optional | 非必填字段 | input:optional |
:valid | 内容符合格式(表单验证) | input:valid |
:invalid | 内容不符合格式 | input:invalid |
:placeholder-shown | 显示占位符状态 | input:placeholder-shown |
✅ 五、目标伪类(跳转目标)
伪类 | 说明 | 示例 |
---|---|---|
:target | 当前 URL 目标元素被激活时 | #section:target |
#faq:target {
background-color: yellow;
}
当用户点击链接
#faq
时,ID 为faq
的元素将被选中。
✅ 六、否定伪类 :not()
用来排除某个选择器,非常强大!
div:not(.active) {
opacity: 0.5;
}
📎 表示:所有不是 .active
的 <div>
透明度为 0.5
也可以嵌套多个选择器:
button:not(:disabled):hover {
background-color: blue;
}
✅ 七、现代伪类(支持情况较新)
伪类 | 说明 | 示例 |
---|---|---|
:is() | 多个选择器的简写组合 | :is(h1, h2, h3) {} |
:where() | 类似 :is() ,但优先级为 0 | :where(.card, .button) |
:has() ✅ Chrome 支持 | 父元素根据子元素状态选择 | div:has(input:focus) |
✅ 八、伪类 vs 伪元素区别(别混淆!)
项目 | 伪类 : | 伪元素 :: |
---|---|---|
作用对象 | 选中某种状态的元素 | 选中元素的一部分(虚构) |
示例 | a:hover | p::before |
使用位置 | 选择器之后 | 选择器之后 |
✅ 九、综合示例
/* 第一个按钮有不同样式 */
button:first-child {
background: green;
}
/* 鼠标悬停时变色 */
a:hover {
text-decoration: underline;
}
/* 所有奇数行变色 */
tr:nth-child(odd) {
background: #eee;
}
/* 仅对启用的按钮添加 hover 效果 */
button:not(:disabled):hover {
background: blue;
}
✅ 十、浏览器支持提示
伪类 | 支持情况 |
---|---|
基本伪类(如 :hover , :first-child ) | ✅ 所有浏览器支持 |
:is() , :where() | ✅ 现代浏览器全面支持 |
:has() | ✅ Chrome/Safari 支持,Firefox ❌ |
如你需要我帮你列出特定伪类的交互示例(如“鼠标悬停显示子菜单”、“选中复选框后显示提示”等),欢迎继续提问!