cliveportman/code

Making inline SVGs responsive

Responsive SVGs aren't as intuitive as you'd expect with some browsers adding whitespace above and below. Optimise it first using the outstanding SVG Editor by Peter Collingridge and envelope it like so:

<div class="svg-container">
<svg>...</svg>
</div>

The method is pretty much the same as used for responsive video, with a padding-bottom on the container element varying according to the width/height ratio:

.svg-container {
 display: block; width: 100%; height: 0; overflow: hidden;
 position: relative;
 padding-bottom: 100%;
 vertical-align: middle;
 }
 .svg-container.logo {
 padding-bottom: 38.9743%;
 }
 .svg-container svg {
 display: block;
 position: absolute; top: 0; left: 0;
 width: 100%; height: 100%;
 }

By default, my SVGs are square, so the padding-bottom is 100%, but the logo on this particular site I'm working is a lot more letterbox so I've added an extra class to that SVG's container.

Hat-tip: a number of sources, most recently Dudley Storey, though none of them worked for me out-of-the-box, presumably because of my bootstrap.