HTML子弹图是用+CSS或SVG实现的非原生可视化组件,含背景条(范围)、主条(实际值)、目标线(目标值)三层结构;纯CSS方案依赖百分比宽度与绝对定位,SVG方案更精准可交互。

什么是 HTML 子弹图(Bullet Chart)?它不是原生 HTML 元素
HTML 本身没有 适合静态数据、仪表盘嵌入、邮件内联样式等场景。关键靠嵌套 当需要缩放不失真、动态更新、绑定 tooltip 或点击事件时,SVG 是更稳妥的选择。重点在于 子弹图出问题,八成卡在比例计算或盒模型上。先检查这几个点: 真正难的不是画出来,而是让不同设备、不同邮件客户端、不同缩放比例下都对齐那根目标线。数值精度、CSS 重置、viewport 设置,一个没控住就偏 2 像素。 标签,子弹图必须用组合方式实现:通常基于 用纯 CSS 实现最简子弹图(无 JS,兼容性好)
position: relative,高度固定(如 24px)background-color + width: 100% 占满width 按比例计算(如实际值 / 最大值 × 100%)::after 伪元素 + border-left 实现,left 值同样按比例算calc() 在 width 中混用单位,建议预计算好百分比值<div class="bullet">
<div class="bullet-bg"></div>
<div class="bullet-bar" style="width: 68%;"></div>
<div class="bullet-target" style="left: 75%;"></div>
</div>
<p>.bullet { position: relative; height: 24px; }
.bullet-bg { background: #e0e0e0; width: 100%; height: 8px; margin: 8px 0; }
.bullet-bar { background: #2196f3; height: 8px; position: absolute; top: 8px; }
.bullet-target::after {
content: ""; border-left: 2px solid #ff5722; height: 16px;
position: absolute; top: 4px; left: 0;
}</p>
用 SVG 实现更精准、可交互的子弹图
的 x/width 计算和 的 x1 定位。
"120px" 错误,应写 120) 而非 ,避免锯齿viewBox + CSS width: 100%,不要设固定 width/height 属性stroke-dasharray 渲染有细微偏移,目标线建议加 shape-rendering="crispEdges"
<svg viewbox="0 0 300 40" class="bullet-svg"><!-- 背景条 --><rect x="0" y="16" width="300" height="8" fill="#e0e0e0"></rect><!-- 主条 --><rect x="0" y="16" width="204" height="8" fill="#2196f3"></rect><!-- 目标线 --><line x1="225" y1="8" x2="225" y2="32" stroke="#ff5722" stroke-width="2" shape-rendering="crispEdges"></line></svg>
常见报错和渲染异常怎么快速定位
width 值为 NaN 或负数 → 检查除零、空字符串转数字(parseInt("") === NaN)getBoundingClientRect() 获取父容器宽后又忘了减去 paddingoverflow: hidden 在父容器,且主条 position: absolute 超出裁剪范围position: absolute 和大部分伪元素,必须退回 table 布局 + 内联样式
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











