How to animate an SVG with CSS
With examples
An SVG inserted inline in the HTML can be animated with CSS just like any element. Here are the most useful techniques.
Requirement: inline SVG
For the CSS to reach the inner shapes, the SVG must be inline in the HTML (not as an img). Give classes or IDs to the shapes you want to animate.
1. Continuous rotation
.spin { transform-box: fill-box; transform-origin: center; animation: spin 2s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } }
transform-box: fill-box makes it rotate around its own center.
2. Stroke that draws itself
.line { stroke-dasharray: 300; stroke-dashoffset: 300; animation: draw 2s ease forwards; } @keyframes draw { to { stroke-dashoffset: 0; } }
A "hand-drawn" effect. Adjust the value to the real length of the stroke.
3. Color change on hover
.icon path { fill: #6c8cff; transition: fill .2s; } .icon:hover path { fill: #ff6c9c; }
4. Scale pulse
@keyframes pulse { 50% { transform: scale(1.15); } } .dot { transform-box: fill-box; transform-origin: center; animation: pulse 1s ease-in-out infinite; }
Tips
- Animate
transformandopacity(they're the smoothest). - Use
transform-box: fill-boxso the origin is the shape itself. - Respect
prefers-reduced-motionfor accessibility.
Prepare your SVG
In svgdesk you create the shape, get clean code and copy the <svg> to paste inline and animate it.