Bootstrap 4 的 .alert 默认无图标,需清除 background-image 并用伪元素或 inline SVG 添加;关闭按钮需覆盖 ::before 或替换 Unicode 字符;多行对齐必须用 d-flex + inline SVG。

Bootstrap 4 的 .alert 根本没有默认图标,所谓“注入”其实是手动占位 + 伪元素渲染
你写 .alert-warning::before { content: "⚠"; } 却看不到图标?不是代码错,是 Bootstrap 4 默认用 background-image 给 .alert 加了底图(比如 info、warning 的 SVG),它会盖住你的伪元素。必须先清掉原背景,再留出文字左侧空间,否则图标和文字重叠或完全不可见。
-
.alert必须加position: relative,否则::before会相对 body 定位 - 清除原背景:
background-image: none !important(v4 的.alert-info等类自带 base64 SVG) - 补左内边距:
padding-left: 2.5rem,为图标+间距留位置 - 伪元素需绝对定位:
left: 1rem; top: 50%; transform: translateY(-50%)才能垂直居中 - 字符图标(如
"\26A0")比字体图标更轻量,但得确认浏览器 Unicode 支持;font-family不要乱设
用 content: url() 插入 SVG 时,URL 编码和尺寸控制是失败主因
直接写 content: url("data:image/svg+xml,<svg>...")</svg> 很容易白屏——SVG 内容必须完整 URL 编码,# 要变 %23, 变 <code>%3C,> 变 %3E;且未设 width/height 会导致图标缩成一个点或溢出。
- 推荐用在线工具(如 svgomg.net)压缩 SVG 后再编码,避免手误
- 在
::before上显式设width: 1.25rem; height: 1.25rem;,别依赖font-size - 颜色用
fill: %23ffc107这种编码值,别写fill: #ffc107(URL 里不认) - 如果图标偏上/偏下,检查是否漏了
top: 50%; transform: translateY(-50%)组合
.close 关闭按钮的图标不能靠 color 改,得换 background-image 或重写 ::before
Bootstrap 4 的关闭按钮是 <button class="close"></button>,里面用 × 字符 + ::before 渲染。但它的 opacity: .5 和 line-height: 1 会让纯改 color 失效,而且字符 × 在高 DPI 屏上边缘模糊。
- 最稳方案:覆盖
.close的::before,设content: "",再用background-image: url(...)塞自定义 SVG - 轻量方案:用 Unicode 字符替换,例如
.close::before { content: "\2715"; font-size: 1.5rem; line-height: 1; }(× 的替代符号) - 必须加
!important,因为 Bootstrap 4 的.close规则优先级很高 - 记得同步调
padding和margin,否则按钮会和右侧边框贴太近
用 inline SVG 更可控,但必须套 d-flex 和加 flex-shrink-0
伪元素方案在多行文本里容易错位,尤其第二行文字会上浮。真正对齐所有行的唯一可靠方式,是把 SVG 写进 HTML,并用弹性布局约束。
立即学习“前端免费学习笔记(深入)”;
- 结构必须是:
<div class="alert alert-warning d-flex align-items-center"> <svg class="flex-shrink-0 me-2" ...>...</svg>警告内容</div> -
flex-shrink-0防窄屏下 SVG 被压缩变形;me-2提供右间距 -
svg必须设width="16" height="16" viewBox="0 0 16 16",且fill="currentColor"才能随.alert-danger等自动变色 - 别漏
role="img" aria-label="Warning",否则屏幕阅读器读不出语义 - 如果项目没预加载 Bootstrap Icons,就别用
<use xlink:href="#exclamation-triangle-fill"></use>,会空白


















