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:hoverp::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 ❌

如你需要我帮你列出特定伪类的交互示例(如“鼠标悬停显示子菜单”、“选中复选框后显示提示”等),欢迎继续提问!

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注