SVG Animation in CSS
CSS animations on SVG elements use the same @keyframes and transition syntax as HTML elements, but SVG has its own set of animatable properties and a few quirks that do not exist in the HTML world. The stroke draw-on effect is the most iconic SVG animation technique: a path that appears to write itself onto the screen. The transform-box fix is the most common gotcha: an icon that rotates around the wrong point until you know the one property that corrects it.
stroke-dasharray and stroke-dashoffset
SVG strokes can be rendered as dashes. stroke-dasharray defines the length of each dash and gap in a repeating pattern. stroke-dashoffset shifts the starting point of that pattern along the path. Together these two properties produce the draw-on effect.
The technique works in three steps:
-
Set
stroke-dasharrayto the total length of the path, making the entire stroke one long single dash. -
Set
stroke-dashoffsetto that same length, which shifts the dash entirely off the visible portion of the path so nothing appears. -
Animate
stroke-dashoffsetfrom the full length to zero, which slides the dash back into position and makes the path appear to draw itself.
@keyframes draw {
to { stroke-dashoffset: 0; }
}
.draw-path {
stroke-dasharray: 200; /* total path length */
stroke-dashoffset: 200; /* start fully hidden */
animation: draw 1.2s ease-out forwards;
}
Measuring Path Length with getTotalLength()
Hardcoding a path length only works if you know it in advance. The reliable approach is to measure it with JavaScript at runtime using getTotalLength() and set the dash values dynamically:
const path = document.querySelector('.draw-path');
const length = path.getTotalLength();
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length;
path.style.animation = 'draw 1.2s ease-out forwards';
This makes the technique work on any path regardless of complexity, without needing to inspect the SVG file for measurements.
If you know the path length at author time (check it in DevTools by selecting the path and running $0.getTotalLength() in the console), you can set it as a CSS custom property directly in the SVG or your stylesheet and avoid the JavaScript entirely. This works well for static icons where the path never changes.
transform-box: fill-box
When you rotate or scale an SVG element with CSS transform, the default transform-box is view-box, which means the transform origin is calculated relative to the entire SVG viewport, not the element itself. Rotating a small circle in the corner of a large SVG will send it spinning around the viewport center rather than its own center.
Setting transform-box: fill-box changes the reference box to the element's own bounding box. Combined with transform-origin: center, this is the fix for virtually every SVG rotation and scale problem:
/* Without fix: rotates around SVG viewport center */
.icon-path {
transform-origin: center;
animation: spin 1s linear infinite;
}
/* With fix: rotates around the element's own center */
.icon-path {
transform-box: fill-box;
transform-origin: center;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
Apply transform-box: fill-box any time a CSS transform on an SVG element does not behave as expected. It is also useful for scale transforms where you want an icon to pulse from its own center rather than from a corner of the viewport.
Fill and Color Transitions
SVG fill, stroke, and opacity are all transitionable. They follow the same rules as CSS color transitions on HTML elements: the browser interpolates between two color values over the transition duration.
.icon-path {
fill: var(--color-text-subtle);
transition: fill 200ms ease-out;
}
.icon-path:hover {
fill: var(--color-accent);
}
A few things do not interpolate:
-
fill: noneto a color value cannot be interpolated. The browser snaps. If you need to transition an element from invisible to colored, useopacityinstead. -
fillset via a presentation attribute (fill="black"on the element) will not respond to a CSS transition unless the CSS rule has sufficient cascade priority to override the attribute. Set fill via CSS, not the presentation attribute, for elements you intend to transition. -
currentColortransitions when the inheritedcolorproperty transitions. If a parent button transitions itscoloron hover, any child SVG usingfill: currentColororstroke: currentColorwill transition automatically.
Looping vs. One-Shot Animations
SVG animations fall into two categories that call for different animation-iteration-count and animation-fill-mode choices.
One-shot animations play once and hold their final state. The draw-on effect, an entrance animation, or a checkmark that appears on form submission are all one-shot. Use animation-fill-mode: forwards so the element stays at its final keyframe after the animation ends. Without it, the path snaps back to invisible the moment the animation finishes.
.draw-path {
animation: draw 1s ease-out forwards; /* forwards keeps it visible */
}
Looping animations run indefinitely. A spinner, a pulsing status dot, or an attention-drawing badge animation are all loops. Use animation-iteration-count: infinite and animation-direction: alternate when the animation should reverse smoothly rather than snap back to the start state.
.spinner-path {
transform-box: fill-box;
transform-origin: center;
animation: spin 0.8s linear infinite;
}
.pulse-dot {
animation: pulse 1.2s ease-in-out infinite alternate;
}
Infinite loops on SVG elements are high-priority targets for prefers-reduced-motion handling. A spinning or pulsing icon that runs for the lifetime of a page visit is one of the most disruptive motion patterns for users with vestibular disorders. The Keyframes and Reduced Motion learning activity covers infinite loops and reduced-motion guards in more depth.
SVG Animation Demo
The checkmark uses the stroke-dashoffset draw-on technique; use Replay in the controls to run it again after it finishes. The spinner loops beside it. Toggle Transform-Box: fill-box to see rotation orbit the wrong point without the fix. Slow Motion stretches the draw duration; Prefers Reduced Motion shows the completed check and pauses the spinner.
Build Your Demo
Create a new directory at unit-6/svg-animation/ in your Practice Site with index.html and svg-animation.css. Your demo must include:
-
At least one draw-on effect using
stroke-dasharrayandstroke-dashoffset. UsegetTotalLength()in JavaScript to measure the path length rather than hardcoding it. -
At least one SVG element that rotates or scales, corrected with
transform-box: fill-boxandtransform-origin: center. -
At least one looping animation and one one-shot animation, demonstrating the correct use of
animation-fill-modeandanimation-iteration-countfor each. -
A
prefers-reduced-motionguard that disables all animations and shows SVG paths in their final visible state for users who prefer reduced motion.
Add a link to your demo on your Practice Site homepage and in your README.md.
Teaching Video Checklist
When you record your teaching video, make sure your teammates come away understanding these concepts:
-
How
stroke-dasharrayandstroke-dashoffsetwork together to hide and reveal a path. Draw a diagram or use a simple short path so the effect is visible clearly at full speed before showing it in slow motion. -
The
transform-boxproblem: show an SVG element rotating withoutfill-boxfirst so teammates see the wrong behavior, then add the fix and show the correct result. The before-and-after is the clearest way to explain why the property matters. -
The difference between one-shot with
forwardsand looping withinfinite alternate. Show what happens to a draw-on animation withoutforwards(snaps back to invisible) and whyalternateprevents the snap in a loop. - Your Practice Site demo: show each animation, toggle reduced-motion emulation in DevTools, and confirm all motion stops and paths appear at their final state.
Build the draw-on effect live during the video starting from a plain visible path with no dash properties set, then add stroke-dasharray, then stroke-dashoffset, then the animation. Each step reveals a different part of how the technique works.
Resources
- MDN: stroke-dashoffset — Attribute reference with animation examples
- MDN: transform-box — Reference for fill-box, view-box, and border-box with SVG context
- MDN: getTotalLength() — JavaScript method for measuring SVG path length
- MDN: animation-fill-mode — forwards, backwards, and both reference