伪元素必须设置content属性才能渲染,常见错误是遗漏;需注意display、vertical-align、定位、可访问性及字体继承问题。
没有 content,::before 和 ::after 不会渲染。哪怕只插一个空格或 Unicode 符号,也得显式写上 content: "" 或 content: "•"。常见错误是只写了样式却漏掉 content,结果什么也不显示。
Unicode 图标最常用,比如箭头、勾选、分隔符:
button::after {
content: "\2714"; /* ✄ */
margin-left: 4px;
}使用字体图标(如 Font Awesome)时,要确保对应字体已加载,并用其私有 Unicode 编码:
.icon-check::before {
font-family: "Font Awesome 5 Free";
content: "\f00c"; /* ✅ */
font-weight: 900;
}想控制宽高、背景、垂直居中或绝对定位,display 必须改。比如在文字旁加小圆点作状态标识:
.status::before {
content: "";
display: inline-block;
width: 8px;
height: 8px;
background: #4CAF50;
border-radius: 50%;
margin-right: 6px;
vertical-align: middle;
}vertical-align: middle 能对齐文本基线,避免上下偏移float:它会脱离文档流,影响后续布局position: absolute 后不配 top/left —— 默认值为 auto,可能意外撑开父容器高度单纯用 text-decoration 很难实现带颜色/粗细/偏移的下划线,这时伪元素更可控。例如给链接加渐变色下划线:
a {
position: relative;
text-decoration: none;
color: #333;
}
a::after {
content: "";
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: linear-gradient(90deg, #FF6B6B, #4ECDC4);
transition: width 0.3s ease;
}
a:hover::after {
width: 100
%;
}position: relative,否则 absolute 伪元素会相对于最近定位祖先定位text-decoration-color + text-underline-offset 做复杂效果——兼容性差(Safari 直到 15.4 才支持 offset)::before 插图标,::after 做下划线,互不干扰伪元素内容不会被屏幕阅读器读出,也不能被复制或搜索。如果图标承载语义(如“必填项”星号),不能只靠 ::after 实现:
.required::after {
content: "*";
color: #f44336;
}同时需要:
aria-hidden="true" 防止星号被读两次.sr-only 类):focus,所以交互反馈(如聚焦时高亮)得作用在真实元素上另外,伪元素不继承 font-family,若父元素用了自定义字体,而图标依赖系统字体(如 emoji),记得单独设 font-family: system-ui, sans-serif。