How-to8 min read

How to Animate SVG Icons with CSS

Hover nudges, spinners, bell swings, icon swaps, and the line-drawing effect in plain CSS, plus why the classic dasharray trick mistimes and how pathLength fixes it.

Sanchez Kim·Published June 16, 2026·Updated October 15, 2026

Icon animation is mostly small stuff: an arrow that nudges forward on hover, a spinner, a checkmark that draws itself after a save. You can do all of it in CSS without a library.

When it goes wrong, it tends to go wrong in the same few ways. The icon rotates around the wrong point, the draw effect finishes in the first quarter of its duration and then sits idle, or nothing happens because the CSS targets path and the icon is built from circles and lines. Below are the techniques, along with those failure points.

Rule one: the markup must be in the DOM

CSS can style only elements it can select. An SVG loaded through <img> or background-image is a sealed image. You can still move, rotate, or fade the box it sits in, which is enough for a spinner, but you can't reach its paths.

For stroke colors, dash offsets, or per-shape timing, the SVG has to be inline: pasted markup, an SVGR import, or an icon component such as lucide-react that renders a real <svg>.

<!-- Only the box can move: CSS can rotate or fade the <img> itself -->
<img class="spin" src="/icons/loader.svg" alt="" width="24" height="24">

<!-- Every shape is reachable: stroke, dash offset, per-path timing -->
<svg class="icon draw" viewBox="0 0 24 24" fill="none"
     stroke="currentColor" stroke-width="2"
     stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
  <circle cx="12" cy="12" r="10" />
  <path d="m9 12 2 2 4-4" />
</svg>

Know what your icon is made of

Before writing selectors, check the shapes inside the icon. I counted the elements in the icon data shipped with two popular sets:

  • Lucide (lucide-react 0.460): 1,539 icons built from 5,363 shapes of seven types: 4,180 path, 444 circle, 366 rect, 276 line, 74 polyline, 15 polygon, and 8 ellipse. Only 155 icons consist of a single element.
  • Tabler outline (@tabler/icons-react 3.36): 4,985 icons, and the node data contains nothing but path elements (plus two g groups).
  • Phosphor: every weight is a filled shape with no stroke, so stroke-based effects (drawing, dash animations) don't apply. Animate transform, opacity, or color instead.

I counted the [tag, attributes] entries in each icon module of lucide-react 0.460.0 (the version Icony ships; alias re-exports skipped) and of @tabler/icons-react 3.36.1. Newer Lucide releases add icons but keep the same drawing rules.

So a selector like .draw path works for every Tabler icon but misses the circle in Lucide's CircleCheck and the rectangles in its calendar icons. Target all drawable shapes with :is(path, circle, rect, line, polyline, polygon, ellipse).

Hover and press feedback

The most useful icon animation is also the simplest: a short transition when the control it belongs to is hovered, focused, or pressed. Put the trigger on the control and the transition on the icon, and include :focus-visible so keyboard users get the same feedback:

.icon-btn svg {
  transition: transform 180ms ease-out, color 180ms ease-out;
}
.icon-btn:hover svg,
.icon-btn:focus-visible svg {
  transform: translateX(3px);        /* arrow nudges forward */
  color: #4f46e5;
}
.icon-btn:active svg {
  transform: translateX(1px) scale(0.95);
  transition-duration: 60ms;         /* press feels immediate */
}

Keep these effects between roughly 100 and 250ms. Anything longer starts to feel like lag on an element people click repeatedly.

Stick to transform and opacity where you can. Browsers can usually animate them without re-running layout, and they don't move surrounding text. Animating width, height, or margin on an inline icon shifts the words next to it.

Spinners

A loading spinner is one keyframe. Use an icon that is already asymmetric, such as an open arc, so the rotation is visible, and use linear timing so it doesn't speed up and slow down on every turn:

<!-- lucide-react 0.460 LoaderCircle: a 3/4 arc on a 24×24 grid -->
<svg class="spinner" viewBox="0 0 24 24" fill="none" stroke="currentColor"
     stroke-width="2" stroke-linecap="round" aria-hidden="true">
  <path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
.spinner {
  animation: spin 0.8s linear infinite;   /* linear: no speed-up/slow-down */
}
@keyframes spin { to { transform: rotate(360deg); } }

Rotating the root <svg> is safe. It's laid out like an inline box, so its default transform-origin is its center. Most “my icon wobbles when it spins” reports come from rotating something else.

Transform origin: the most common bug

Elements inside an SVG (a <path>, a <g>) don't use their own bounding box as the reference for transforms. By default the origin is the top-left of the SVG's coordinate system, so rotate() on a path swings it around the icon's corner, and scale() pulls it toward that corner.

Use transform-box: fill-box to measure from the shape's own bounds, then set the origin relative to that. For swinging motions (a bell, a hanging tag), move the origin to the pivot point:

/* Rotating a shape INSIDE the SVG (e.g. a gear in a larger icon) */
.icon .gear {
  transform-box: fill-box;      /* measure the origin from the shape itself */
  transform-origin: center;
  animation: spin 2s linear infinite;
}

/* Swinging a bell from its top edge: rotate the whole <svg> */
.bell:hover svg {
  transform-origin: 50% 10%;
  animation: ring 0.6s ease-in-out;
}
@keyframes ring {
  0%, 100% { transform: rotate(0); }
  20% { transform: rotate(14deg); }
  40% { transform: rotate(-12deg); }
  60% { transform: rotate(8deg); }
  80% { transform: rotate(-4deg); }
}
Three circle-check icons. In the middle one the rotated check has moved outside the icon to the left; on the right it is rotated in place inside the circle.
Only the check path is rotated 90deg. With the default transform box its center moves from (12, 12) to (−12, 12) in viewBox units, outside the icon; with fill-box it stays at (12, 12). Dashed line = the 24×24 viewBox, drawn with overflow: visible. Headless Chromium.

Lucide's bell has its body at the top and the clapper as a separate path at the bottom. The artwork hangs from the top, so swinging the whole icon from a point near there looks right. Pick the origin by looking at the drawing, not by default.

The line-drawing effect, done correctly

The draw-in effect uses two stroke properties. stroke-dasharray turns the line into dashes and gaps, and stroke-dashoffset slides that pattern along the path. If a single dash is as long as the path and it's offset by that same length, the line starts invisible, and animating the offset to zero draws it.

Most tutorials use a fixed value such as 100 for both. That works, but the real lengths are far shorter, so most of the animation goes to waste. Measured with getTotalLength() in Chromium:

  • Lucide Check (M20 6 9 17l-5-5): 22.63 units.
  • Tabler IconCheck (M5 12l5 5l10 -10): 21.21 units.
  • Heroicons outline CheckIcon (m4.5 12.75 6 6 9-13.5): 24.71 units.
  • Lucide CircleCheck: 62.43 units for the circle (2π × 10 would be 62.83; Chromium approximates), only 8.49 for the check inside.

With dasharray: 100 the visible length at offset d is min(100 − d, path length), so the 22.63-unit check is complete long before the offset reaches zero. I ran both versions for 1 second, linear, and measured how much of the finished check was on screen every 25ms:

Line chart of the share of the check drawn over one second. The dasharray 100 line reaches 100% at about 225 ms and stays flat; the pathLength 1 line rises steadily to 100% at 1000 ms.
Lucide Check at 96 CSS px, 1000ms linear, sampled every 25ms by pausing the animation in headless Chromium. Drawn = dark pixels at that moment ÷ dark pixels of the finished icon.

The fixed-value version was fully drawn by the 225ms sample and sat idle for the remaining 775ms. Most of the timing is wasted, and the effect feels rushed. On CircleCheck the circle and the check finish at completely different times.

The pathLength attribute fixes this. It tells the browser to treat the shape's length as whatever number you give, so every shape measures 1 and the same CSS works for all of them. It's part of SVG 2 and applies to every shape element. As with any SVG feature, check it in the browsers you support, and fall back to measured lengths if a shape misbehaves:

<svg class="icon draw" viewBox="0 0 24 24" fill="none" stroke="currentColor"
     stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <circle cx="12" cy="12" r="10" pathLength="1" />
  <path d="m9 12 2 2 4-4" pathLength="1" />
</svg>
.draw > * {
  stroke-dasharray: 1;          /* one dash as long as the whole shape */
  stroke-dashoffset: 1;         /* shifted fully out of view */
  animation: draw 600ms ease-out forwards;
}
.draw > :nth-child(2) { animation-delay: 450ms; }  /* check after circle */

@keyframes draw { to { stroke-dashoffset: 0; } }
Two rows of eight frames of a circle-check drawing in. Top row with dasharray 100: the circle is complete by 300 ms and the check is already complete in the 600 ms frame. Bottom row with pathLength 1: the circle and then the check draw gradually.
The CSS above on Lucide CircleCheck (600ms ease-out per shape, check delayed 450ms), frames from 0 to 1050ms. Top: the same timing with dasharray and offset 100 instead of pathLength. Headless Chromium.

A circle's stroke starts at its rightmost point (3 o'clock). If you want the ring to draw from the top, rotate the circle by -90deg with transform-box: fill-box and transform-origin: center, as in the transform-origin section.

When the icon comes from a component library, you can't add pathLength to its internal shapes in JSX. Add it at runtime instead. The helper below also stores each shape's index in a custom property so the shapes draw one after another:

// For icons rendered by a component library, where you can't add
// pathLength in the markup: normalise every drawable shape at runtime.
const SHAPES = 'path, circle, rect, line, polyline, polygon, ellipse';

export function prepareDraw(svg) {
  svg.querySelectorAll(SHAPES).forEach((el, i) => {
    el.setAttribute('pathLength', '1');
    el.style.setProperty('--i', String(i));   // index for staggering
  });
}
.draw :is(path, circle, rect, line, polyline, polygon, ellipse) {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  animation: draw 500ms ease-out forwards;
  animation-delay: calc(var(--i, 0) * 120ms);
}
import { useEffect, useRef } from 'react';
import { CircleCheck } from 'lucide-react';
import { prepareDraw } from './prepareDraw';

export function SuccessMark() {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current) prepareDraw(ref.current);
  }, []);
  // lucide-react forwards the ref and className to the <svg>
  return <CircleCheck ref={ref} className="draw" aria-hidden="true" />;
}

If you prefer real lengths (to keep the drawing speed constant across icons of different sizes), read them with element.getTotalLength(), which works on every SVG shape element, and set the dasharray and offset to that value instead.

Swapping between two icons

Menu-to-close, play-to-pause, and copy-to-check transitions are usually two icons cross-faded, not one icon morphed. Morphing paths needs matching point structures, which unrelated icons don't have. Stack both icons in the same grid cell and let the control's state drive them:

<button class="menu-toggle" aria-expanded="false" aria-label="Menu">
  <svg class="i-open"  …><!-- menu (three lines) --></svg>
  <svg class="i-close" …><!-- x --></svg>
</button>
.menu-toggle { display: grid; }
.menu-toggle svg {
  grid-area: 1 / 1;                     /* stack both icons in one cell */
  transition: opacity 150ms, transform 200ms ease-out;
}
.menu-toggle .i-close { opacity: 0; transform: rotate(-90deg); }
.menu-toggle[aria-expanded="true"] .i-open  { opacity: 0; transform: rotate(90deg); }
.menu-toggle[aria-expanded="true"] .i-close { opacity: 1; transform: none; }

Tying the animation to aria-expanded has a useful side effect. The visual state can't drift out of sync with what screen readers announce, because both come from the same attribute.

Respect reduced motion without breaking meaning

Operating systems let people ask for less motion, and CSS exposes it through prefers-reduced-motion. The common snippet turns every animation off, but decorative motion and motion that carries information deserve different treatment.

A draw-in is decoration: skip it and show the finished icon. A spinner tells the user something is happening. Replace its rotation with a gentle opacity pulse instead of freezing it, or the page looks stalled.

@media (prefers-reduced-motion: reduce) {
  /* Decorative motion: remove it */
  .draw > *, .draw :is(path, circle, rect, line, polyline, polygon, ellipse) {
    animation: none;
    stroke-dashoffset: 0;               /* show the finished drawing */
  }
  .bell:hover svg { animation: none; }
  .icon-btn svg, .menu-toggle svg { transition-duration: 0.01ms; }

  /* Status motion: keep the signal, lose the spin */
  .spinner { animation: pulse 1.6s ease-in-out infinite; }
}
@keyframes pulse { 50% { opacity: 0.4; } }

Also avoid anything that flashes more than three times a second. WCAG 2.3.1 sets that threshold for content that could trigger seizures, and a fast-blinking notification badge can cross it.

Mistakes that make icon animations misfire

  • Animating a filled icon's stroke. Heroicons solid, Bootstrap, Radix, and Phosphor have no stroke to draw. Use scale, opacity, or color.
  • Forgetting forwards. Without animation-fill-mode: forwards, a drawn icon snaps back to invisible when the animation ends.
  • Selecting only path. Lucide uses seven shape types; the circle, rectangle, or line you missed will sit there fully drawn while the rest animates.
  • Hovering the icon instead of the control. The icon is a small target. Trigger the effect from the button or link so the whole hit area responds.
  • Rotating inner shapes without transform-box. The shape orbits the icon's top-left corner instead of turning in place.
  • Endless decorative loops. A bouncing icon that never stops competes with the content. Loop only things that represent ongoing state.

When CSS isn't enough

Reach for a JavaScript animation library (Motion, GSAP) or a Lottie file when you need to sequence many steps with interruptions, respond to scroll or drag position, or morph between shapes. For hover states, spinners, draw-ins, and swaps, CSS is smaller, has no dependency, and is easier for the next developer to read.

If you start from an exported icon, for example a recolored SVG copied from Icony, the export hard-codes the color and size you chose. For animated UI icons, swap the hex for currentColor and remove the fixed width and height so your CSS controls both.

Try it in Icony

Search 10,000+ open-source icons, customize color, size, and stroke, then copy or download as SVG, PNG, or a React component — free.

Open the icon customizer

Related guides