最稳方案是用 svg 的两个 实现环形图:背景环固定,进度环通过 stroke-dasharray 设总周长(≈282.74),stroke-dashoffset 动态计算(circumference - percent% × circumference),配合 text-anchor="middle" 和 dominant-baseline="middle" 居中文字。

用 <svg></svg> + <circle></circle> 画百分比环形图最稳
纯 CSS 实现的“圆环进度条”在 Safari 或旧版 Edge 上容易出错,stroke-dasharray 计算稍有偏差就断开或重叠。直接上 SVG 是零基础也能快速跑通的方案,关键是理解两个 <circle></circle>:一个做背景环,一个做进度环。
核心思路是把圆周长(2 * π * r)当作 100% 的基准值,再按百分比截取对应长度的虚线段。r 取 45(留 5px 边距),viewBox 设为 "0 0 100 100",这样数值直观好算。
-
r固定设为45,cx/cy都为50,确保居中 - 圆周长 =
2 * Math.PI * 45 ≈ 282.74,这个数必须用在stroke-dasharray和stroke-dashoffset中 - 进度环的
stroke-dashoffset=282.74 - (percent / 100) * 282.74,即“从哪开始画” - 务必给背景环设
stroke="#e0e0e0"、进度环设stroke="#4CAF50",否则看不出差异
stroke-dasharray 和 stroke-dashoffset 别写反
这是新手卡住最多的地方:把 stroke-dasharray 当成“画多长”,把 stroke-dashoffset 当成“画到哪”,其实刚好相反。
stroke-dasharray="282.74, 282.74" 表示“画 282.74,空 282.74”,也就是只显示第一段实线;stroke-dashoffset 是整体往左平移的距离 —— 数值越大,进度环看起来越“少”。
- 0% 时:
stroke-dashoffset="282.74"→ 进度环完全不可见 - 50% 时:
stroke-dashoffset="141.37"→ 半环 - 100% 时:
stroke-dashoffset="0"→ 满环 - 别用百分比单位(如
"100%"),SVG 中必须是数字
动态更新要改 stroke-dashoffset,不是 stroke-dasharray
想用 JS 更新进度?只改 stroke-dashoffset 就够了。stroke-dasharray 可以固定写死,它只是定义“总长+空白”的循环模式,不需要随百分比变化。
将调研报告、方案对比、数据分析、需求梳理、会议纪要、设计说明、代码评审、学习笔记等任务产物输出为可在浏览器直接打开的单文件 HTML,替代 Markdown 作为最终交付物。Markdown 在信息密度、视觉清晰度和可分享性上已跟不上 AI 产物的丰富度,HTML 能同时承载排版、表格、SVG 等。
例如绑定到 input range:
<input type="range" min="0" max="100" id="progress"><svg viewbox="0 0 100 100"><circle cx="50" cy="50" r="45" fill="none" stroke="#e0e0e0" stroke-width="8"></circle><circle cx="50" cy="50" r="45" fill="none" stroke="#4CAF50" stroke-width="8" stroke-dasharray="282.74" stroke-dashoffset="282.74" id="progress-ring"></circle></svg>
JS 部分只需:
const ring = document.getElementById('progress-ring');
const input = document.getElementById('progress');
const circumference = 2 * Math.PI * 45;
<p>input.addEventListener('input', () => {
const offset = circumference - (input.value / 100) * circumference;
ring.style.strokeDashoffset = offset;
});</p>
文字居中显示百分比要绕开 text-anchor 坑
直接用 <text x="50" y="50"></text> 文字会偏下,因为默认 baseline 对齐。想让“50%”真正居中,得调 dominant-baseline="middle" 和 text-anchor="middle"。
-
x="50"+y="50"是中心坐标 - 必须同时设
text-anchor="middle"(水平居中)和dominant-baseline="middle"(垂直居中) - 字号建议设
font-size="14",太大压边,太小看不清 - 别用
<center></center>或 CSStransform: translate(),SVG 内部坐标系不认这些
环形图本身不难,但圆周长计算、offset 方向、文字锚点这三处,只要漏掉一个,效果就立刻不对。动手前先拿计算器算一遍 45 的周长,比反复试更省时间。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










