CSS伪类选择器大全:提升网页交互与样式的神奇工具
CSS伪类选择器是前端开发中不可或缺的强大工具,它们允许我们根据元素的状态、位置或用户行为动态地应用样式。本文将全面介绍常用的伪类选择器,并通过代码示例展示其实际应用场景。
基础交互伪类
1. 超链接状态伪类
html
<style>
a:link { color: green; } /* 未访问链接 */
a:visited { color: purple; } /* 已访问链接 */
a:hover { color: blue; } /* 鼠标悬停 */
a:active { color: red; } /* 激活状态(点击时) */
</style>
<a href="#">示例链接</a>
记忆口诀 :Love Hate (LVHA) - :link
> :visited
> :hover
> :active
2. 表单元素伪类
css
input:focus { border-color: yellow; } /* 获取焦点时 */
input:disabled { opacity: 0.5; } /* 禁用状态 */
input:checked { background: green; } /* 选中状态 */
结构位置伪类
1. 基础子元素选择
html
<style>
/* 1.html */
p:nth-child(2n) { color: red; } /* 偶数段落变红 */
</style>
<div>
<p>段落1</p> <!-- 不变 -->
<p>段落2</p> <!-- 红色 -->
</div>
2. 类型过滤选择
html
<style>
/* 3.html */
p:first-of-type { color: red; } /* 第一个<p>变红(跳过前面的<span>) */
</style>
<div>
<span>其他元素</span>
<p>第一个段落</p> <!-- 红色 -->
<p>第二个段落</p>
</div>
3. 高级公式选择
选择器格式 | 说明 |
---|---|
:nth-child(2n) |
选择偶数元素(2,4,6...) |
:nth-child(2n+1) |
选择奇数元素(1,3,5...) |
:nth-child(4n+1) |
每4个中的第1个(1,5,9...) |
:nth-last-child(2) |
倒数第2个子元素 |
实际应用(demo3效果.html):
css
.item-list img:nth-child(4n+1) { margin-left: 0; } /* 每行第1张图去左边距 */
.item-list img:nth-child(4n) { margin-right: 0; } /* 每行第4张图去右边距 */
特殊状态伪类
css
:empty { display: none; } /* 隐藏空元素 */
:not(.ignore) { font-weight: bold; } /* 反向选择 */
:target { animation: highlight 1s; } /* URL锚点目标 */
实战案例
新闻列表样式
css
/* 第一条新闻特殊样式 */
.nav a:first-child {
font-size: 18px;
background: #ccc;
display: block; /* 独占一行 */
}
/* 奇偶行span不同背景 */
.nav a:nth-child(2n) span { background: #e5a7b2; }
.nav a:nth-child(2n+1) span { background: #e9d2da; }
完整参考手册
推荐查阅MDN官方文档获取最新最全的伪类列表: MDN CSS伪类文档
小贴士:伪类选择器可以组合使用,如
a:hover:first-child
表示鼠标悬停时的第一个子链接。
通过合理使用伪类选择器,可以极大提升网页的交互体验和视觉效果,而无需编写大量JavaScript代码!