content 属性必不可少,否则伪元素不渲染;支持空字符串、字面符号、Unicode 转义、URL 和 attr();字体图标需严格匹配 font-family 与 font-weight;vertical-align: middle 和 display: inline-block 是对齐关键;绝对定位需父元素设 position: relative。

必须写 content,否则图标根本不会出现
这是最常踩的坑:只写了 color、background 或 font-size,却漏掉 content。浏览器会直接忽略整个伪元素,哪怕样式全对也白搭。
content 值可以是:
-
content: ""(空字符串,适合纯背景色块或边框) -
content: "★"(字面符号,支持中文、箭头、星号等) -
content: "\2714"(Unicode 转义,注意是\不是\u) -
content: url(./icons/home.svg)(路径相对于 CSS 文件位置) -
content: attr(data-icon)(读取 HTML 中的data-icon属性值)
用字体图标(如 Font Awesome)时,font-family 和 font-weight 必须配对
比如 Font Awesome 6 的 solid 图标要写 font-weight: 900,regular 图标则用 400;font-family 名称必须和 @font-face 中定义的完全一致(大小写、空格、引号都不能错)。
常见错误示例:
立即学习“前端免费学习笔记(深入)”;
/* ❌ 错误:拼错 font-family 或漏 font-weight */
.icon::before {
content: "\f00c";
font-family: "FontAwesome"; /* 应为 "Font Awesome 6 Free" */
}
<p>/<em> ✅ 正确 </em>/
.icon::before {
content: "\f00c";
font-family: "Font Awesome 6 Free";
font-weight: 900;
display: inline-block;
}图标对不齐?vertical-align: middle 比 top: Xpx 更可靠
伪元素默认是 display: inline,会参与文本流,但基线对齐容易偏移。用 vertical-align: middle 可让图标垂直居中于文字行高,不受字体大小变化影响。
需要精确控制尺寸或定位时,加 display: inline-block 是标配:
- 不加它,
width/height无效 - 不加它,
margin在某些浏览器里表现异常 - 配合
vertical-align: middle才能稳定对齐
想绝对定位图标?父元素必须设 position: relative
如果直接给 ::before 写 position: absolute; right: 0;,它会相对于最近的「已定位祖先」定位——而这个祖先可能是 body,导致图标飞到页面右上角。
正确做法:
- 宿主元素(比如
button或.nav-link)加position: relative - 再在
::before上设position: absolute+top/right等偏移 - 记得预留空间:用
padding-right或margin-right避免文字被遮挡
复杂点在于:伪元素不能响应事件,也不能被 JS 选中;如果图标需要点击或状态反馈,就得换成真实 <span> 元素——::before 只负责“看起来像”。



















