Animation with pseudo-classes (:hover)
SVGs can be 'animated' by using CSS to manipulate different properties. Common things to change are:
- fill
- stroke
- transform properties (rotation, position, scale, skew)
It is easiest to use a pseudo-class like :hover
to trigger these animations.
Below we have a simple SVG circle with a gray fill. We're using the hover state to change the fill to pink.
<svg id="ex1" version="1.1" xmlns="http://www.w3.org/2000/svg">
<style>
#ex1 circle {
fill: gray;
}
#ex1 circle:hover {
fill: pink;
}
</style>
<circle cx="75" cy="75" r="75" />
</svg>
If you had a more complicated shape, you could animate just part of it by adjusting your selector.
Here we have two circles. We'll change the color of the smaller circle whenever we hover over the entire SVG image.
<svg id="ex2" version="1.1" xmlns="http://www.w3.org/2000/svg">
<style>
#ex2 .outer {
fill: gray;
}
#ex2 .inner {
fill: red;
}
#ex2:hover .inner {
fill: pink;
}
</style>
<circle class="outer" cx="75" cy="75" r="75" />
<circle class="inner" cx="25" cy="25" r="25" />
</svg>
Add a Transition
The key to making these changes look more graceful is to add a CSS transition. This will simply "transition" the specified property change. You can read up on the transition property on the Mozilla Develop Network.
Taking the first example, we can modify it to transition the fill change over a period of time. It's important to note that the transition should go on the initial state of the element rather than the changed state.<svg id="ex3" version="1.1" xmlns="http://www.w3.org/2000/svg"> <style> #ex3 circle { fill: gray;
transition: fill .5s ease-in;
} #ex3 circle:hover { fill: pink; } </style> <circle cx="75" cy="75" r="75" /> </svg>
More Examples
A careful and thoughtful implementation of these techniques can yield very sophisticated results. A fantastic example of this is the delightful demonstration by the makers of the Iconic icons set. This was a proof of concept on animating SVG icons.
Also check out this set of animated icons on Code Pen.
Additional Resources
For more information on SVG animation, see the resources below.
- Styling And Animating SVGs With CSS
- Design the Web: SVG Rollovers with CSS [Lynda.com]
- CSS Animation Chapter 4: Applying CSS Animations to SVG [Lynda.com]