CSS 伪元素
学习 ::before/::after/::first-line/::selection · 难度:进阶 · +15XP
CSS 伪元素完全指南
伪元素(Pseudo-elements)允许你为元素的特定部分设置样式,或者创建虚拟的额外元素而无需修改 HTML 结构。它们是 CSS 中最强大的特性之一。
常用伪元素一览
| 伪元素 | 语法 | 作用 |
|---|---|---|
::before | p::before | 在元素内容之前插入内容 |
::after | p::after | 在元素内容之后插入内容 |
::first-line | p::first-line | 选中文本首行 |
::first-letter | p::first-letter | 选中文本首字 |
::selection | ::selection | 用户选中的文本部分 |
::placeholder | input::placeholder | 表单占位文字 |
::marker | li::marker | 列表项标记 |
::before 和 ::after
这两个是最常用的伪元素,必须配合 content 属性使用:
/* 基本用法 — 添加装饰内容 */
.quote::before {
content: '"';
font-size: 3em;
color: #ccc;
line-height: 0;
vertical-align: middle;
}
.quote::after {
content: '"';
font-size: 3em;
color: #ccc;
vertical-align: middle;
}
清除浮动(经典用法)
.clearfix::after {
content: '';
display: table;
clear: both;
}
自定义列表标记
li::marker {
color: #2196F3;
font-size: 1.2em;
content: '>';
}
首字下沉效果
article p:first-of-type::first-letter {
float: left;
font-size: 4em;
line-height: 0.8;
font-weight: bold;
margin-right: 8px;
color: #c0392b;
font-family: Georgia, serif;
}
自定义选中颜色
::selection {
background: #ffeb3b;
color: #333;
}
/* 特定元素 */
.highlight::selection {
background: #e91e63;
color: white;
}
复杂装饰 — 引号徽章
.badge {
position: relative;
display: inline-block;
padding: 6px 12px;
background: #4CAF50;
color: white;
}
.badge::after {
content: attr(data-count); /* 使用自定义属性 */
position: absolute;
top: -8px;
right: -8px;
background: red;
color: white;
border-radius: 50%;
width: 20px;
height: 20px;
font-size: 12px;
display: flex;
align-items: center;
justify-content: center;
}
注意事项
::before和::after必须有content属性,即使为空也要写content: ''- 伪元素默认是
inline元素,需要设置display来改变 - 伪元素不属于 DOM,无法通过 JavaScript 直接操作
- CSS3 规范使用双冒号
::,CSS2 使用单冒号:,建议使用双冒号 - 一个选择器最多只能有一个
::before和一个::after ::first-line只对块级元素有效
伪元素是 CSS 中极具创造力的工具。通过巧妙运用伪元素,你可以在不增加 HTML 标签的情况下实现丰富的视觉效果,保持代码简洁。