Appearance
作用:表示元素的特定状态或在结构中的特定位置。它不会改变 DOM,而是捕捉用户交互、元素顺序等动态条件。
1. 动态交互伪类
:hover—— 鼠标悬停时。:focus—— 元素获得焦点时(常用于输入框、按钮)。:active—— 元素被激活时(如鼠标按下但未松开)。
css
button:hover {
background-color: #0056b3;
}
button:active {
background-color: #003d80;
}
2. 结构伪类
根据元素在父容器中的位置来选择。
:first-child/:last-child—— 父元素下第一个或最后一个子元素。:nth-child(n)—— 选择父元素下第 n 个子元素(n从 1 开始计数)。:nth-child(odd)/:nth-child(even)隔行变色常用。
:first-of-type/:last-of-type/:nth-of-type(n)—— 在兄弟元素中按同类型排序。
css
li:first-child {
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
/* 表格条纹背景 */
p:first-of-type {
font-size: 1.2em;
}
/* 选择父元素中第一个 <p> 段落,忽略其他类型元素排序 */
3. 其他常用伪类
:not(selector)—— 排除匹配选择器的元素。:empty—— 没有子元素(包括文本节点)的元素。:checked—— 被选中的复选框或单选框。
css
a:not(.external) {
text-decoration: none;
}
/* 除带有 .external 类的链接外,取消下划线 */
注意:伪类是单冒号 :,而伪元素(如 ::before、::after)是双冒号,两者概念不同,不要混淆。