CSS Animations with SVG

Because inline SVG elements are part of the Document Object Model (DOM), you can style and animate them using the same CSS properties you use for regular HTML elements.

This is often the easiest way to animate SVGs, especially for simple UI feedback like hover states or basic loops.

CSS Transitions

The transition property allows you to change property values smoothly (from one value to another) over a given duration. This is perfect for simple interactions like hover effects.

CSS Keyframe Animations

For more complex, looping, or multi-step animations, you can use @keyframes. This works exactly like it does with HTML elements.

Handling Transformations

When animating the transform property (like rotate() or scale()) on an SVG element, there is one important property you should know: transform-box.

By default, SVG elements use the SVG viewport as the coordinate system for transformations. This means a rotation might happen around the top-left corner of the whole SVG, rather than the center of the shape itself. To fix this, you can use the following:

Example: CSS Animated SVG

In this example, the square has a continuous CSS rotation and changes color when you hover over it.

View Output

Limitations of CSS

While CSS is great for transforms and colors, it has some limitations when it comes to SVG:

If you need to move objects along a complex path or morph one shape into another, you'll want to use SMIL, which we'll cover in the next few pages.