对于html,里面有伪类选择器,
-
:hover
- 当鼠标悬停在元素上时应用样式。
a:hover { color: red; }
-
:active
- 当元素被激活(如被点击)时应用样式。
button:active { background-color: blue; }
-
:focus
- 当元素获得焦点时应用样式,通常用于输入框。
input:focus { border: 2px solid green; }
-
:first-child
- 选择父元素的第一个子元素。
p:first-child { font-weight: bold; }
-
:last-child
- 选择父元素的最后一个子元素。
p:last-child { font-style: italic; }
-
:nth-child(n)
- 选择父元素的第 n 个子元素,可以使用公式。
li:nth-child(2) { color: orange; /* 选择第二个子元素 */ } li:nth-child(odd) { background-color: lightgray; /* 选择所有奇数子元素 */ }
-
:not(selector)
- 选择不匹配指定选择器的元素。
div:not(.active) { opacity: 0.5; }
-
:checked
- 选择被选中的复选框或单选框。
input[type="checkbox"]:checked { background-color: yellow; }
-
:disabled
- 选择禁用状态的输入元素。
input:disabled { background-color: lightgray; }
使用示例
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
a:hover {
color: red;
}
li:nth-child(odd) {
background-color: lightgray;
}
input:focus {
border: 2px solid green;
}
</style>
</head>
<body>
<a href="#">悬停我</a>
<ul>
<li>项目 1</li>
<li>项目 2</li>
<li>项目 3</li>
</ul>
<input type="text" placeholder="点击我">
</body>
</html>