Responsive SVG

SVGs are just amazing. The more I explore them, the more I really appreciate all they can do. The problem I was running into was that I couldn’t use them in a responsive design because they would not respond to their container’s width. I was wrong, they can, it just takes some work.

Here’s a simple line drawn in SVG:

[CodePen height=300 show=result href=absvc user=larsmiller ]

As you can see, by clicking on HTML above, the SVG has a width of 160 and a height of 90. Since all of the data inside of the SVG (lines, paths, rectangles, circles, etc.) are positioned based on these absolute widths and heights, making the width into 100% and height auto simply won’t work. The result is using a method that I first saw for embedding videos in a responsive way. Basically, you wrap your SVG¬†in a div with a height of 0 and padding-bottom of XXX% That XXX should be calculated as height divided by width, or in this case 90 / 160 = 56.25%. Then, we remove the width and height of the SVG altogether. Add a viewbox and¬†preserveAspectRatio attributes and we’re set! Here’s the result:

[CodePen height=300 show=result href=Aikju user=larsmiller ]

Using this principle, we can do really fun things like masking an image with some defined paths (like our eyespeak logo).

[CodePen height=300 show=result href=DEcti user=larsmiller ]

Lars Miller

Lars is a front-end and WordPress developer.