CSS伪类选择器
伪类选择器根据元素的特殊状态或位置来匹配元素,以单冒号 : 开头。
语法格式
CSS
选择器:伪类 {
属性: 值;
}
状态伪类
CSS
/* 鼠标悬停 */
a:hover {
color: red;
}
/* 激活状态(点击时) */
button:active {
background: #333;
}
/* 获得焦点 */
input:focus {
border-color: blue;
}
/* 已访问链接 */
a:visited {
color: purple;
}
/* 未访问链接 */
a:link {
color: blue;
}
结构伪类
CSS
/* 第一个子元素 */
li:first-child {
font-weight: bold;
}
/* 最后一个子元素 */
li:last-child {
border-bottom: none;
}
/* 第 n 个子元素 */
li:nth-child(2) {
color: red;
}
/* 奇数位 */
li:nth-child(odd) {
background: #eee;
}
/* 偶数位 */
li:nth-child(even) {
background: #fff;
}
/* 倒数第 n 个 */
li:nth-last-child(2) {
color: blue;
}
/* 同类型第一个 */
p:first-of-type {
font-size: 18px;
}
/* 同类型最后一个 */
p:last-of-type {
margin-bottom: 0;
}
表单伪类
CSS
/* 禁用状态 */
input:disabled {
opacity: 0.5;
}
/* 启用状态 */
input:enabled {
background: white;
}
/* 选中状态 */
input:checked {
border-color: blue;
}
/* 必填字段 */
input:required {
border-color: red;
}
/* 有效输入 */
input:valid {
border-color: green;
}
/* 无效输入 */
input:invalid {
border-color: red;
}
其他伪类
CSS
/* 否定伪类 */
p:not(.special) {
color: gray;
}
/* 目标伪类(锚点) */
section:target {
background: yellow;
}
/* 空元素 */
div:empty {
display: none;
}
/* 只有文本的元素 */
p:only-child {
color: blue;
}
注意:伪类选择器权重为10,与类选择器相同。
要点总结
- 状态伪类:
:hover:active:focus等匹配交互状态 - 结构伪类:
:first-child:nth-child(n)匹配位置 - 表单伪类:
:disabled:checked匹配表单状态 :not()否定伪类可排除特定元素
存放路径:articles/CSS/入门/CSS选择器/CSS伪类选择器.md
📝 发现内容有误?点击此处直接编辑