How do I build a donut chart with an animated percentage?
A ring that fills to a set value shows progress or a result at a glance. We use an SVG circle with stroke-dasharray, and animate the number with CSS only through @property.
Steps
- Draw two circles in SVG, one for the track and one for the progress, and give the progress circle pathLength="100" so the value maps straight to a percentage.
- Store the value in a variable: style="--p: 75", and set stroke-dasharray: var(--p) 100.
- Animate the ring with @keyframes from stroke-dasharray: 0 100 to the final value.
- Register --n with @property as an integer and animate it, then print it with counter() inside ::after. counter(n, arabic-indic) shows Arabic-Indic digits.
- Put role="img" and an aria-label with the full value on the wrapper. With reduced motion, show the final ring and number at once.
The code
HTML
<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Donut Percentage</title>
<style>
@property --n { syntax: "<integer>"; inherits: false; initial-value: 0; }
body { min-height: 100vh; display: grid; place-items: center; margin: 0; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; }
.donut { --p: 75; position: relative; inline-size: 180px; aspect-ratio: 1; }
.donut svg { inline-size: 100%; block-size: 100%; transform: rotate(-90deg); }
.track, .fill { fill: none; stroke-width: 12; }
.track { stroke: #e6e6ef; }
.fill { stroke: #6c5ce7; stroke-linecap: round; stroke-dasharray: var(--p) 100;
animation: ring 1.2s cubic-bezier(.2,.8,.2,1) both; }
.num { position: absolute; inset: 0; display: grid; place-items: center; font-size: 2rem; font-weight: 700;
counter-reset: n var(--n); animation: count 1.2s cubic-bezier(.2,.8,.2,1) both; }
.num::after { content: counter(n) "%"; } /* use counter(n, arabic-indic) for ٧٥٪ style digits */
@keyframes ring { from { stroke-dasharray: 0 100; } }
@keyframes count { from { --n: 0; } to { --n: 75; } }
@media (prefers-reduced-motion: reduce) {
.fill, .num { animation: none; }
.num { --n: 75; }
}
</style>
<div class="donut" role="img" aria-label="النسبة 75 بالمئة">
<svg viewBox="0 0 44 44" aria-hidden="true">
<circle class="track" cx="22" cy="22" r="16"/>
<circle class="fill" cx="22" cy="22" r="16" pathLength="100"/>
</svg>
<span class="num" aria-hidden="true"></span>
</div>
</html>Related categories: Numbers & Counters · Animated Charts