SASS mixin for responsive SVGs
After listening to Sara Soueida on Shop Talk Show we finally have a reliable way to use SVGs in responsive sites, our old method was to yell at the SVG and change every possible value within the SVG and in CSS until it looked right in most browsers.
She goes into a ton of detail in this amazing post which we use as the basis of our mixin code:
There’s A LOT in this post, the section we’re most interested in is titled SVG embedded using iframes. Apparently iframes use the same technique as inline SVGs which is the method we’re using. Using SVGs inline is preferred because it gives you much more control with CSS.
Take some time to understand how it works before blindly pasting the code below into your site.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// apply the mixin to the div that surrounds your svg // get the svg width and height from the viewbox attribute of the SVG // see: http://mimoymima.com/sass-mixin-responsive-svgs/ @mixin responsive-svg($svgwidth, $svgheight, $containerwidth){ width: $containerwidth; // sizes the svg margin: 0 auto; // centers the svg height: 0; padding-top: #{($svgheight/$svgwidth)*$containerwidth}; position: relative; svg { position: absolute; top: 0; left: 0; } } |
You need to have a container around your SVG (as outlined in Sara’s post). You call the mixin within the container in your SASS, so if your container had a class of “svg-container” you’d do something like this:
1 2 3 4 5 |
.svg-container { @include responsive-svg(45, 72, 3em); // arguments are ($svgwidth, $svgheight, $containerwidth) } |
It took me a while to get this working so hopefully this snippet saves someone else some time.
Happy coding ya’ll