In this tutorial I’ll explain how to create responsive SVG images; more specifically, I’ll explain how to create SVG logos, icons, and images, which change depending on the screen they’re displayed with.
Responsive SVG Images
Let’s begin with a demo. Here’s what we’re working towards (check out the full screen version for maximum effect):
If you resize the container (hat tip to Rick Strahl for his jQuery Resizable plugin) or the browser window, you’ll see the SVG respond.
Nested inside our svg we need to define some symbols; each of our components will have its own symbol. Here’s what a symbol looks like, including, in this case, a viewBox of 60×60 (matching the dimensions of our icon).
<symbol id="icon" viewBox="0 0 60 60">
Now we paste the contents of our SVG icon within the symbol element, but only the path elements for the flag and the castle. We end up with:
We have a whole bunch of code now, but if you open the SVG in your browser you won’t see anything. We’ve defined our symbols, but we still need to actually use them. Let’s directly place three use elements on our canvas; one for each version:
Here we begin by hiding the landscape and full versions by default.
Then at screens of at least 500px we hide the square and reveal the landscape.
Then at screens of at least 1200px we keep the square hidden, hide the landscape, and reveal the full version.
And we’re done! Save the SVG file and you’ll be able to use it just like a normal image (with an img element). Don’t forget you can check out the full screen version to get a full impression of the responsive effect we’ve created.