Animated SVG Icons
Animated icons provide subtle but effective feedback to users. One of the most common examples is the "Hamburger" menu icon that transforms into an "X" when clicked.
SVG is the perfect tool for this because you can animate the individual lines or even morph the entire shape using the techniques we've learned.
The Hamburger to "X" Transition
There are two main ways to achieve this transition:
- CSS Transforms: Rotate the top and bottom lines and hide the middle line. This is the simplest method and highly performant.
- Path Morphing (SMIL/JS): Literally move the coordinates of the path points to create the "X" shape. This allows for more organic or unique transitions.
Example: Interactive Menu Icon
In the example below, click the hamburger icon to see it morph into an "X" using a combination of SMIL path data animation and opacity.
Accessibility for Animated Icons
When an icon changes its state (like a hamburger menu becoming an "X"), it's crucial that users with assistive technologies (like screen readers) can understand what the icon represents and its current state. SVG provides two primary tags for this:
<title>: Acts like a "label" for the SVG. It's often displayed as a tooltip when a user hovers over the element.<desc>: Provides a longer, more detailed description of the SVG's purpose or complex content.
In the example above, we've enhanced the <svg> tag with several accessibility features:
Accessibility Best Practices
- Speed: Keep transitions fast (usually between 200ms and 400ms). Aim for "snappy" rather than sluggish.
- ARIA Attributes: Use
role="img"to tell the browser the SVG is an image andaria-labelledbyto link the title and description to the image. - Functional Feedback: The animation should serve a purpose, such as clearly indicating that a menu is now open or that a task is complete.