Chapter 4. Creating a Responsive SVG Sprite
The “scalable” part of SVG is perhaps the most powerful aspect of the graphics format. Using the viewBox attribute and our knowledge of shapes and paths, we can crop an SVG to any size on the fly, knowing that our intentions within the coordinate space will be preserved.
If we remove the width and height attributes from a common SVG, we’ll see something interesting. The SVG expands itself to the full width of the viewport, maintaining the aspect ratio of everything within the DOM.
If we use CSS keyframes or JavaScript to move SVG elements such as circle or path while scaling this SVG up or down, the increments that they will move will scale as well, along with the graphic. This means that if you scale a complex SVG using percentages, a flexbox, or other techniques, your animation will scale accordingly. You don’t have to adjust anything for mobile or other sizes; you can focus on writing the code correctly one time.
The completed animation is completely scalable. In the following CodePen example, you can randomly resize the animation while it’s running and watch it instantly adjust. This is very useful for responsive development. The animation in Figure 4-1 uses a completely fluid approach.
Figure 4-1. Different states of the same animation at different sizes
We design the whole thing first, and then slowly reveal things. Figure 4-2 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access