You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在styled-components的伪元素(::before/::after)中使用FontAwesome图标

伪元素使用Font Awesome图标不生效修复方案

现有代码错误点

  • Unicode写法错误:content属性中字体图标转义前缀应为反斜杠\而非正斜杠/,且你当前填写的f0是不完整的Font Awesome图标编码,完整编码为4位十六进制字符,比如铅笔图标对应编码为f040
  • CSS语法错误:::before 规则中font-weight: 900;后多余了字符c,会导致整段伪元素规则失效
  • 需确认项目已正确引入对应版本的Font Awesome字体资源,否则指定font-family也无法渲染图标

修正后代码示例

export const WriteButton = styled.button`
    position:relative;
    width:170px;
    height:50px;    
    padding-left:40px;
    padding-right:20px;
    margin-top:20px;
    background:transparent;
    border:1px solid #ececec;
    outline:none;
    font-size:14px;

    ::before{
        content: "\f040";
        position:absolute;
        top:0;
        right:0;
        font-size:30px;
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
    }
`

export const WriteButtonIco = styled(Pen)`
    position:absolute;
    top:50%;
    left:20px;
    width:20px;
    height:20px;
    color:#111;
    z-index:2;
`

额外注意事项

  • 如果你使用的是Font Awesome 6版本,需要将font-family改为 "Font Awesome 6 Free"
  • 免费版的Solid样式图标才需要设置font-weight:900,Regular样式免费版不可用,若要使用需确认你购买了Pro授权

内容的提问来源于stack exchange,提问作者Hyemin Jeong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:54:08