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

如何不使用Icomoon、Fontello,仅用HTML、CSS实现类Bootstrap Icons的SVG展示

实现自定义SVG图标类(fi fi-alert)展示alert.svg

方法一:CSS背景图实现(单图标场景)

这是最直接的实现方式,通过CSS背景图绑定图标文件:

  1. 将alert.svg放在项目目录中(比如/assets/icons/alert.svg)
  2. 编写CSS样式:
/* 基础图标容器样式 */
.fi {
  display: inline-block;
  width: 24px; /* 按需调整图标尺寸 */
  height: 24px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

/* 绑定alert.svg的类 */
.fi-alert {
  background-image: url('/assets/icons/alert.svg');
}
  1. HTML中直接调用:
<i class="fi fi-alert"></i>

方法二:SVG Sprite实现(多图标场景)

如果需要使用多个自定义图标,推荐用Sprite模式减少HTTP请求:

  1. 创建SVG Sprite文件(比如/assets/icons-sprite.svg),将alert.svg的内容嵌入为symbol:
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
  <symbol id="alert" viewBox="0 0 24 24"> <!-- viewBox需与原alert.svg一致 -->
    <!-- 粘贴alert.svg内部的path等图形代码,示例: -->
    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
  </symbol>
</svg>
  1. 在HTML页面中引入Sprite文件(建议放在<body>开头):
<svg style="display: none;">
  <use href="/assets/icons-sprite.svg#alert"></use>
</svg>
  1. 编写CSS样式:
.fi {
  display: inline-block;
  width: 24px;
  height: 24px;
}

.fi svg {
  width: 100%;
  height: 100%;
  fill: currentColor; /* 图标颜色继承父元素文字色,方便自定义 */
}
  1. HTML调用方式:
<i class="fi fi-alert">
  <svg><use href="#alert"></use></svg>
</i>

实用技巧

  • 修改width/height可快速调整图标大小
  • 给.fi-alert添加background-color或修改fill值,可自定义图标颜色
  • 确保SVG文件路径正确,避免出现404错误

内容的提问来源于stack exchange,提问作者Asliddin Mahmudov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:24:20