如何在CSS伪元素:before/:after中使用可复用自托管SVG图标
完全可以实现,有两种成熟方案都能满足你SVG图标跨CSS类复用的需求,其中第二种方案的使用体验和Font Awesome指定content编码的形式高度一致:
方案1:直接引用自托管的SVG文件
将你的SVG图标存到项目静态资源目录后,直接在伪元素的content属性中引入资源路径即可,示例代码如下:
/* 基础图标样式 */ .icon-home::before { content: url('/assets/icons/home.svg'); display: inline-block; width: 16px; height: 16px; vertical-align: middle; margin-right: 4px; } /* 其他CSS类复用该图标 */ .nav-home-item::before { content: url('/assets/icons/home.svg'); /* 按需调整尺寸、边距等样式 */ width: 20px; height: 20px; }
如果需要通过CSS修改图标颜色,只要把SVG文件内部的fill/stroke属性值改为currentColor,图标就会自动继承父元素的color属性值。
方案2:SVG转Data URI内嵌到CSS(更贴近Font Awesome使用体验)
你可以把SVG内容编码为Data URI后,定义为CSS全局变量,需要使用的地方直接调用变量即可,不需要单独托管SVG文件,复用效率更高:
/* 全局定义所有图标变量,统一维护 */ :root { --icon-home: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor'%3E%3Cpath d='M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z'/%3E%3C/svg%3E"); --icon-search: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3C/svg%3E"); } /* 封装通用图标类,和Font Awesome使用逻辑完全一致 */ .icon::before { display: inline-block; vertical-align: middle; margin-right: 4px; } .icon.icon-home::before { content: var(--icon-home); width: 16px; height: 16px; } .icon.icon-search::before { content: var(--icon-search); width: 16px; height: 16px; } /* 其他CSS类复用也可以直接调用变量 */ .search-bar::after { content: var(--icon-search); width: 18px; height: 18px; color: #999; }
小提示:对SVG内容做URL编码即可,不需要转Base64,体积更小,也支持
currentColor继承颜色属性。
内容的提问来源于stack exchange,提问作者Gangula
相关产品推荐
相关产品推荐

