Responsive SVG Examples

by Erin

HTML

<h2>Image source SVG file example (not interactive)</h2>
<p>Image rules for responsive nature apply here, don't set specific values use fluid values (i.e. percentages).</p>
<br />
<img src="http://info.sonicretro.org/images/f/f0/Classic_sonic_run3.svg" />
<br /><hr /><br />
<h2>Backgound image SVG Example (not interactive)</h2>
<p>Set the SVG to be the background image of an element. Use 'contain' for the background-size, for the padding divide the width and height and multiply by 100%. Use normal responsive rules on the wrapper and the background will adjust as expected.</p>
<br />
<div class="svg__bg"><!-- background here --></div>
<br /><hr /><br />
<h2>Inline SVG Example (interactive)</h2>
<p>Do not include width/height values on the SVG element. You may need to adjust your viewBox values so that the image is within the container. Use preserveAspectRatio="xMidYMid meet" for older browser support.</p>
<br />
<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://web.resource.org/cc/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.0" viewBox="0 0 468 363" preserveAspectRatio="xMidYMid meet" id="svg2">
  <defs id="defs33">
    <linearGradient inkscape:collect="always" id="linearGradient4574">
      <stop style="stop-color:white;stop-opacity:1;" offset="0" id="stop4576"/>
      <stop style="stop-color:white;stop-opacity:0;" offset="1" id="stop4578"/>
    </linearGradient>
    <linearGradient id="linearGradient2778">
      <stop style="stop-color:#8883dd;stop-opacity:1;" offset="0" id="stop2780"/>
      <stop style="stop-color:white;stop-opacity:1;" offset="1" id="stop2782"/>
    </linearGradient>
    <linearGradient inkscape:collect="always" xlink:href="#linearGradient4574"...

CSS

body,
html {
  text-align: center;
}
img,
svg,
.svg__bg {
  width: 50%;
  height: auto;
  margin: 0 auto;
  display: block;
  border: 1px solid #000;
}
.svg__bg {
   background-image: url(http://lurkmore.so/images/f/fe/Emily_the_strange_01.svg);
   background-size: contain;
   background-repeat: no-repeat;
   background-position: center center;
   height: 0;
   padding: 0; /* reset */
   padding-bottom: calc(100% * 744.094 / 1052.36); /* width / height */
 }
 h2 {
   font-size: 1.2em;
   font-weight: bold;
 }