贝利信息

css 伪元素与文本装饰_如何通过 ::before 和 ::after 插入图标或符号

日期:2026-01-19 00:00 / 作者:P粉602998670
伪元素必须设置content属性才能渲染,常见错误是遗漏;需注意display、vertical-align、定位、可访问性及字体继承问题。

伪元素插入内容必须设置 content 属性

没有 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-wei

ght: 900; }

伪元素默认是 inline,但常需 display: inline-block 或 block

想控制宽高、背景、垂直居中或绝对定位,display 必须改。比如在文字旁加小圆点作状态标识:

.status::before {
  content: "";
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #4CAF50;
  border-radius: 50%;
  margin-right: 6px;
  vertical-align: middle;
}

文本装饰类场景:下划线、删除线、强调符号的灵活组合

单纯用 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%;
}

容易被忽略的继承与可访问性问题

伪元素内容不会被屏幕阅读器读出,也不能被复制或搜索。如果图标承载语义(如“必填项”星号),不能只靠 ::after 实现:


.required::after {
  content: "*";
  color: #f44336;
}

同时需要:

另外,伪元素不继承 font-family,若父元素用了自定义字体,而图标依赖系统字体(如 emoji),记得单独设 font-family: system-ui, sans-serif