css伪类选择器具体用法
时间: 2025-05-27 11:25:06 浏览: 20
### CSS伪类选择器的具体用法
CSS伪类选择器是一种用于匹配元素特定状态的选择器,它使得开发者可以基于用户的交互行为或者页面结构的变化来定义样式。以下是常见的几种伪类选择器及其具体用法和示例代码。
#### `:link` 和 `:visited`
`:link` 用于未访问过的链接,而 `:visited` 则针对已访问过的链接。这两种伪类通常一起使用以区分不同状态下的超链接颜色或其他样式[^3]。
```css
a:link {
color: blue;
}
a:visited {
color: purple;
}
```
#### `:hover`, `:active`, and `:focus`
这些伪类分别表示鼠标悬停、点击激活以及获得焦点的状态。它们常被用来增强用户体验,比如按钮高亮显示或输入框聚焦时的效果[^3]。
```css
button:hover {
background-color: lightgray;
}
button:active {
transform: scale(0.98);
}
input:focus {
outline: 2px solid green;
}
```
#### `:focus-within`
当某个容器内的子元素获取到焦点时,该容器会应用此伪类所指定的样式。这对于表单控件特别有用[^3]。
```css
div:focus-within {
border: 2px dashed orange;
}
```
#### `:target`
如果一个URL指向了一个ID,则带有相应ID的HTML元素将成为目标元素,并可由`:target`伪类选中并施加特殊样式。
```css
section:target {
background-color: yellow;
}
```
#### `:root`
`:root` 表示文档的根元素,在 HTML 中总是指代 `<html>` 元素。它可以作为全局变量的作用域起点[^3]。
```css
:root {
--main-bg-color: white;
}
body {
background-color: var(--main-bg-color);
}
```
#### `:checked`
适用于单选按钮 (`<input type="radio">`) 或复选框 (`<input type="checkbox">`) 被选中后的样式调整[^3]。
```css
label input[type=checkbox]:checked + span {
text-decoration: line-through;
}
```
以上就是部分常用CSS伪类选择器的功能介绍及其实现方式的例子。利用好这些工具可以帮助构建更加动态且互动性强的网站界面。
阅读全文
相关推荐


















