-- online Search!

Bringing SVGs to Life With CSS, SMIL, and JavaScript

by kirupa   |   filed under Web Animation

TL;DR

To animate an SVG, first check where it lives. Our page's CSS and JavaScript can animate an inline svg element, while an SVG loaded with img only runs the CSS and the animation tags (called SMIL) inside its own file. CSS handles colors, spins, and line drawing, SMIL moves shapes along paths, and JavaScript handles motion driven by data.

  • An SVG loaded with img or as a CSS background is sealed off from our page, so only the CSS keyframes and SMIL written inside the file can animate it.
  • SVG shapes rotate around the SVG's 0, 0 point by default, so we add transform-box: fill-box and transform-origin: center to spin a shape in place.
  • A line draws itself when we set pathLength="1" and stroke-dasharray: 1 on the path and animate stroke-dashoffset from 1 to 0.
  • Safari ignores the CSS d property, so a path morph that works in every browser uses SMIL's animate element or JavaScript.

An SVG is a picture made out of instructions: draw a circle here, a curvy line there, and fill this shape with orange. Because those shapes are real elements instead of a grid of pixels, we can change their colors, positions, and even their outlines over time. That is how logos spin, checkmarks draw themselves, and little dots race along a map.

The tricky part is that there are three ways to animate an SVG, and which ones work depends on how our SVG got onto the page. We are going to walk through all three, fix the rotation gotcha that bites just about everyone, and build the famous line-drawing effect along the way.

Onwards!

Three Little SVG Animations

Before we look at any code, here is what we will build. Each panel below animates an SVG a different way:

Try it

  1. Uncheck Use fill-box and watch the sun
  2. Press Replay to draw the squiggle again
  3. Press Pause under the red dot

The sun spins and glows with plain CSS. The squiggle draws itself with a trick on its outline (aka its stroke), and the red dot follows its track using tags inside the SVG. Unchecking Use fill-box sends our sun swinging around the corner, which is a really common bug.

Where Does Our SVG Live?

An SVG that we paste right into our HTML as an <svg> element (aka an inline SVG) can be styled and scripted by our page, just like a div. An SVG that we load as a file, with <img src="sun.svg"> or as a CSS background-image, is treated like a photo. Our page's CSS and JavaScript can't reach the shapes inside it. Here is the same sun loaded both ways:

On the left, our sun is an inline svg element inside our page, and arrows show page CSS and page JS both reaching it, each with a green check. On the right, the sun is loaded with img src="sun.svg". Arrows from page CSS and page JS stop at red X marks before the image's thick border, and inside the image are two tags: @keyframes and SMIL.

On the left, our page's CSS and JavaScript can change the sun's circle and rays. On the right, our sun.svg file is sealed off. Only animations written inside the file run, as CSS @keyframes in a <style> block or as SMIL tags (more on those later). JavaScript inside the file doesn't run at all.

There are a bunch of other ways to put an SVG on a page, and How to Display an SVG in HTML, CSS, and JavaScript covers them. From here on, our SVGs will be inline.

Animating Colors and Transforms With CSS

Many things we set on SVG shapes, like fill, stroke, opacity, and transform, are regular CSS properties, so CSS can animate them. Here is the markup for our sun, which is a circle and eight rays inside a g (group) element:

<svg viewBox="0 0 200 120">
  <g class="sun">
    <circle cx="100" cy="60" r="22" />
    <line x1="100" y1="30" x2="100" y2="18" />
    <!-- ...and seven more rays -->
  </g>
</svg>

To make our sun glow and spin, we write keyframes just like we would for any HTML element:

.sun {
  animation: spin 6s linear infinite;
}

.sun circle {
  fill: #ffb703;
  animation: glow 3s ease-in-out infinite alternate;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes glow {
  to {
    fill: #fb5607;
  }
}

Our circle's fill will go from yellow (#ffb703) to orange-red (#fb5607) and back, and the whole group will turn once every 6 seconds. For a color change on hover, a transition on fill works just as well.

Why Does My SVG Rotate Around the Wrong Point?

If we run this CSS as is, our sun won't spin in place. It will swing in a giant circle instead. HTML elements rotate around their own center, but SVG shapes rotate around the point 0, 0 of the SVG's coordinate system, which for our viewBox is the top-left corner. Here is rotate(25deg) with and without a fix:

Two copies of our 200 by 120 SVG with a faded sun at 100, 60 showing where it started. On the left, with the default origin, rotate(25deg) swings the sun around the top-left corner, marked with a red dot and a note saying Spins around this corner, so it lands lower and to the left and its bottom rays are cut off. On the right, with transform-box: fill-box, the same rotate(25deg) turns the sun in place around the dot at its center.

On the left, our sun at 100, 60 turned 25 degrees around the corner. It ended up lower and to the left, and the edge cut part of it off. On the right, it turned in place. The fix is two more lines of CSS:

.sun {
  transform-box: fill-box;
  transform-origin: center;
  animation: spin 6s linear infinite;
}

Setting transform-box to fill-box tells the browser to measure transform-origin against the shape's own bounding box (the smallest rectangle that fits around it) instead of the whole SVG. Now center means the center of our sun, in every major browser.

Can CSS Animate an SVG's Shape?

Partly. A circle's center and radius (cx, cy, and r) are CSS properties in Chrome, Edge, Firefox, and Safari, but the CSS d property for changing a path's outline doesn't work in Safari. Animating a radius looks as follows:

.dot {
  transition: r 0.3s ease-out;
}

.dot:hover {
  r: 30px;
}

A dot that starts with r="10" grows to a radius of 30 when we hover over it. Paths are trickier. The CSS d property describes a path's outline, like d: path("M 10 10 L 190 10 Z"), and Chrome, Edge, and Firefox can animate between two outlines. Safari reads the property but ignores it (as of December 2026, according to MDN).

There's a catch even where d works. The browser morphs one path into another by pairing up their numbers, so both paths need the same commands in the same order. Here is a play button turning into a stop button:

A play triangle morphing into a stop square at 0%, 50%, and 100%. Both shapes have four points numbered 1 to 4. Points 1 and 4 stay put. Points 2 and 3 both start at the triangle's tip, and at 50% they are halfway to the square's top-right and bottom-right corners, with a note saying Point 3, halfway to its partner. A dashed outline shows the starting triangle.

Both shapes have four points. Points 1 and 4 stay put, while points 2 and 3 start together at the triangle's tip and slide apart to the square's two right corners. What if the point counts didn't match? The browser would just jump to the new shape. For a morph that works everywhere, SMIL's <animate> element can animate a path's d attribute, or we can fake it with the tricks from Creating a Morph Animation Without Actually Morphing.

How Do We Make an SVG Line Draw Itself?

We give our path one dash that is exactly as long as the path, and then we animate stroke-dashoffset to slide that dash into view. With pathLength="1" on the path, that means stroke-dasharray: 1 and a stroke-dashoffset that goes from 1 to 0.

The stroke-dasharray property normally gives us dashed lines. A value of 1 means a 1-unit dash, then a 1-unit gap, repeating forever, and stroke-dashoffset slides that pattern along the path. Here is our squiggle unrolled into a straight line, with the pattern at three offsets:

Our path unrolled into a straight line from 0 to 1, with a repeating dash and gap pattern on three rows. At offset 1, the dash sits just before the path starts and the gap covers the whole path, so nothing is drawn. At offset 0.5, the dash covers the first half of the path, so it is half drawn. At offset 0, the dash covers the whole path, so it is all drawn.

At an offset of 1, our dash sits just before the path starts, and the gap covers the whole path. At 0.5, the dash has slid halfway in, and at 0, it covers everything. Going from 1 to 0 looks like someone drawing our line. Here are those same three moments on our actual squiggle:

Our squiggle at three moments. At offset 1, none of it is drawn, 0.0 of 251.1 units. At offset 0.5, the first half is drawn in blue, 125.6 of 251.1 units. At offset 0, the whole squiggle is drawn, 251.1 of 251.1 units.

Why 1, though? Our squiggle is really 251.1 units long, and every path has its own awkward length. The pathLength attribute lets us pick a length, and the browser scales every dash and offset to match. With pathLength="1", the start of our squiggle is 0, the end is 1, and the middle is 0.5:

Our squiggle with five marks along it. With pathLength="1", the marks are 0, 0.25, 0.5, 0.75, and 1. Their real lengths are 0, 62.8, 125.6, 188.3, and 251.1.

This means the same few lines will draw any path, no matter how long it is. First, our path gets pathLength="1":

<path id="squiggle" pathLength="1"
      d="M 20 90 C 50 20, 90 20, 100 60
         S 150 110, 180 30" />

Next, our CSS sets up the dash and slides it in:

#squiggle {
  fill: none;
  stroke: #0798ff;
  stroke-width: 8;
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  animation: draw 2.5s ease-in-out forwards;
}

@keyframes draw {
  to {
    stroke-dashoffset: 0;
  }
}

The forwards keyword keeps our line drawn when the animation ends. Safari only added pathLength in version 14, so many older tutorials measure the path with JavaScript instead:

const squiggle = document.querySelector("#squiggle");
const length = squiggle.getTotalLength(); // 251.11...

squiggle.style.strokeDasharray = length;
squiggle.style.strokeDashoffset = length;

Our draw keyframes then take the offset from 251.11 down to 0. As a bonus, we have the real length handy, so longer lines can take longer to draw.

What Is SMIL, and Does It Still Work?

SMIL is a set of animation elements, like <animate>, <animateTransform>, and <animateMotion>, that live inside an SVG's markup. It works in Chrome, Edge, Firefox, and Safari today, and because it lives in the SVG itself, it keeps working when that SVG is loaded with an <img> tag.

The name stands for Synchronized Multimedia Integration Language, which is a mouthful! Our red dot uses <animateMotion> to follow a path, and here is what each part of its markup does:

Markup for our dot: circle r="9", then animateMotion dur="4s" repeatCount="indefinite", then mpath href="#track". Notes beside it say the circle is What moves, dur and repeatCount are How long, how often, and mpath is The road it follows. Below, a purple dashed figure-eight labeled #track has a red dot on it.

The circle is what moves. The dur and repeatCount attributes say the trip takes 4 seconds and repeats forever, and <mpath> points at the path whose id is track. Our full SVG looks as follows:

<svg id="dotSvg" viewBox="0 0 200 120">
  <path id="track" fill="none" stroke="#c3ccd6"
        d="M 100 60 C 140 10, 190 10, 190 60
           C 190 110, 140 110, 100 60
           C 60 10, 10 10, 10 60
           C 10 110, 60 110, 100 60 Z" />
  <circle r="9" fill="#e0605a">
    <animateMotion dur="4s" repeatCount="indefinite">
      <mpath href="#track" />
    </animateMotion>
  </circle>
</svg>

Our circle has no cx or cy, because <animateMotion> moves its 0, 0 point along the track. An <animate> element changes one attribute over time, and <animateTransform> changes a transform. Here is our sun glowing and spinning with SMIL instead of CSS:

<g>
  <circle cx="100" cy="60" r="22" fill="#ffb703">
    <animate attributeName="fill"
             values="#ffb703; #fb5607; #ffb703"
             dur="6s" repeatCount="indefinite" />
  </circle>
  <!-- ...our eight rays -->
  <animateTransform attributeName="transform"
    type="rotate" from="0 100 60" to="360 100 60"
    dur="6s" repeatCount="indefinite" />
</g>

A SMIL rotate takes an angle and then the point to rotate around, so 0 100 60 means 0 degrees around our sun's center. There's no transform-origin gotcha here! From JavaScript, the <svg> element's pauseAnimations() and unpauseAnimations() methods will pause and resume SMIL, which is what our demo's Pause button does.

Animating SVGs With JavaScript

When our SVG is inline, every shape in it is a DOM element. Just about anything JavaScript can do to a div, it can do to a circle, and that includes the Web Animations API's animate method:

const sun = document.querySelector(".sun");

const spin = sun.animate(
  [
    { transform: "rotate(0deg)" },
    { transform: "rotate(360deg)" }
  ],
  { duration: 6000, iterations: Infinity }
);

spin.pause(); // later: spin.play(), spin.reverse()...

Our sun still needs transform-box: fill-box from earlier. In return, we get an Animation object that we can pause, reverse, speed up, or wait on. Web Animations and the Animate Method goes into the details.

When an animation is driven by data, like a dot that tracks how far we've scrolled, we can calculate every frame ourselves with requestAnimationFrame. This code moves a circle with an id of dot along our track without any SMIL:

const dot = document.querySelector("#dot");
const track = document.querySelector("#track");
const length = track.getTotalLength();

function move(time) {
  const progress = (time / 4000) % 1;
  const distance = progress * length;
  const point = track.getPointAtLength(distance);

  dot.setAttribute("cx", point.x);
  dot.setAttribute("cy", point.y);
  requestAnimationFrame(move);
}

requestAnimationFrame(move);

The getPointAtLength method gives us the x and y of any spot along a path, and our progress could come from a scroll position or a slider instead. For big, choreographed sequences, libraries like GSAP add timelines and path morphing that work everywhere. GSAP has been free since April 2025, plugins included, but it's still extra JavaScript to download.

CSS vs. SMIL vs. JavaScript: Which Should You Use?

Use CSS for most SVG animations, because hovers, spins, color changes, and line drawing all work without any JavaScript. Use SMIL when an SVG has to animate on its own inside an <img> or needs a path morph that works everywhere, and use JavaScript when the animation depends on data or needs controlling while it runs.

Each choice has a cost. CSS can't morph paths in Safari or follow live data. SMIL's syntax is old and clunky, fewer developers know it, and a media query can't turn it off. JavaScript is the most flexible, but it can't reach into an SVG loaded with <img>, and a library means more code to download. Here is how they stack up:

QuestionCSSSMILJavaScript
Animates inside an SVG loaded with <img>?Yes, when it's in the fileYesNo
Morphs a path in every browser?No, Safari ignores dYesYes, with our own math or a library
Pause, reverse, or jump around while running?Pause, and not much elsePause and jumpAll of them
Follows live data or input?NoNoYes
Turns off with a reduced motion media query?YesNo, it needs JavaScriptYes, by checking it first

When in doubt, start with CSS. Most of the time, it's all we will need.

Keeping SVG Animations Smooth and Kind

Some SVG properties cost more to animate than others. When we change transform or opacity, the shape stays the same, so the browser has little to recalculate. A growing blur filter is different, because the browser will compute the whole blur again on every frame:

Two rows of three frames. On the left, labeled transform, opacity, our sun moves and turns across frames 1, 2, and 3, with a note saying Same shape, just moved and a green check. On the right, labeled filter: blur(), the sun gets blurrier across frames 1, 2, and 3, with a note saying A new blur every frame and a red X.

The bigger the blur, the more work each frame takes. Hundreds of moving paths are expensive too, since they all get redrawn. If an SVG animation stutters, check the filters and the number of moving shapes first.

Some people get dizzy or sick from motion, so they ask their devices for less of it. Browsers pass that along through the prefers-reduced-motion media query, and our CSS can listen for it:

@media (prefers-reduced-motion: reduce) {
  .sun,
  .sun circle {
    animation: none;
  }

  #squiggle {
    animation: none;
    stroke-dashoffset: 0;
  }
}

Our squiggle needs one more line, since a stroke-dashoffset of 1 would hide it forever. Setting the offset to 0 shows the line fully drawn. SMIL ignores media queries, so we will check the setting in JavaScript and pause our dot:

const query = "(prefers-reduced-motion: reduce)";

if (window.matchMedia(query).matches) {
  document.querySelector("#dotSvg").pauseAnimations();
}

Our demo keeps its buttons working, so people can still press Play or Replay on purpose. Respecting Reduced Motion goes much deeper.

Conclusion

Phew! We covered a lot of ground. The first thing to figure out is where our SVG lives, because an SVG loaded with <img> only animates with the CSS and SMIL inside its own file. From there, CSS handles colors, spins (with transform-box: fill-box, of course), and lines that draw themselves. SMIL moves things along paths and morphs shapes everywhere, and JavaScript takes over when an animation has to react to data.

There are a few rough edges. Safari ignores the CSS d property, and SMIL's syntax feels like it came from another decade (because it did). Even so, our sun, squiggle, and little red dot only needed a handful of lines each. Now go make something spin...around the right point, of course!

Before you go, here are a few things you can do:

  1. Ask a question

    Stuck on something, or curious about a detail we skipped? Ask on the forums, and we’ll help you out.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright © KIRUPA 2026 //--