伪类(Pseudo-classes)和伪元素(Pseudo-elements)是 CSS 中用于增强选择器功能的两个重要概念。虽然它们名称相似,但用途和行为有本质区别。以下从基础到深度应用的系统解析:
特性 | 伪类(:hover) | 伪元素(::before) |
---|---|---|
作用对象 | 选择元素的特定状态 | 创建元素的虚拟子元素 |
语法符号 | 单冒号(CSS3 后兼容双冒号) | 双冒号(CSS3 规范) |
DOM 可见性 | 不修改 DOM 结构 | 不实际存在于 DOM 中 |
典型示例 | :hover, :active, :nth-child() | ::before, ::after, ::first-line |
/* 多状态叠加控制 */
button:not(:disabled):hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
/* 结合兄弟选择器 */
input:checked ~ .toggle-label {
background: #4CAF50;
border-color: #388E3C;
}
/* 表格斑马纹 + 悬停高亮 */
tr:nth-child(odd):hover {
background: #f8f9fa;
}
/* 无效表单的视觉反馈 */
input:invalid:focus {
border-color: #e53935;
animation: shake 0.3s ease-in-out;
}
/* 选择前3个非隐藏元素 */
.item:not(.hidden):nth-child(-n+3) {
opacity: 0.9;
border-left: 3px solid #2196F3;
}
/* 动态生成带图标的按钮 */
.btn-download::after {
content: url('download-icon.svg');
margin-left: 8px;
vertical-align: middle;
}
/* 使用 data-* 属性动态显示内容 */
.tooltip::before {
content: attr(data-tooltip);
position: absolute;
white-space: nowrap;
background: #333;
color: white;
padding: 4px 8px;
border-radius: 3px;
opacity: 0;
transition: opacity 0.3s;
}
/* 渐变边框效果 */
.card::before {
content: '';
position: absolute;
inset: 0;
border-radius: 16px;
padding: 2px;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}
/* 文字背景装饰 */
h2::before {
content: '';
display: block;
width: 40px;
height: 4px;
background: #FFC107;
margin-bottom: 12px;
border-radius: 2px;
}
/* 加载进度指示器 */
.loading-bar::after {
content: '';
position: absolute;
width: 0%;
height: 3px;
background: #3F51B5;
animation: progress 2s ease-out forwards;
}
@keyframes progress {
to { width: 100%; }
}
/* 悬停展开效果 */
.menu-item::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
width: 0;
height: 2px;
background: #E91E63;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.menu-item:hover::after {
left: 0;
width: 100%;
}
.tab-item:active::before {
transform: scale(0.95);
opacity: 0.6;
}
.input-field:focus::after {
transform: scaleX(1);
background: #2196F3;
}
/* 移动端显示简化内容 */
@media (max-width: 768px) {
.complex-label::before {
content: '简版: ';
color: #999;
}
}
.card:hover::before {
transform: perspective(1000px) rotateX(15deg);
box-shadow: 0 20px 40px rgba(0,0,0,0.2);
}
伪元素层级管理
使用 z-index
控制堆叠上下文时,确保父元素有定位属性
GPU 加速策略
优先使用 transform
和 opacity
属性实现动画
内容更新优化
动态修改 content
属性会导致重绘,高频操作需谨慎
选择器复杂度控制
避免 .parent:hover .child::before
的多层嵌套结构
/* 临时显示伪元素边界 */
.debug::before {
outline: 2px solid red !important;
box-shadow: 0 0 0 2px blue inset !important;
}
通过深入理解这些特性,开发者可以:
关键要把握两者的核心差异:伪类关注状态选择,伪元素专注内容生成,二者的组合使用能极大扩展 CSS 的表现力。