4

I've been trying out using SVGs on a few of the latest projects, and since it scales, I was wondering what's your take on dynamic height and width of these SVGs?

So far, I've exported graphics from Illustrator, saving them as SVGs, opened the SVG and removed the doctype and #layer_1 etc IDs. And then I've edited the height and width attributes to 100%. So I've adjusted the size of the SVG by setting width and/or padding on their parent. This makes it easy to adjust the size with media queries. As well as CSS transitions. But I'm not sure this is the best way of doing it.

My HTML has been like this:

<div class="svg icon_phone">
  <img src="static/icon_phone.svg">
</div>

<div class="svg">
  <img src="static/icon_other.svg">
</div>

CSS like this:

.svg {
  width: 60%;
}

.icon_phone {
  padding-left: 80px;
}

And the SVG would look like this:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     height="100%" width="100%" viewBox="0 0 97 94.5" enable-background="new 0 0 97 94.5" xml:space="preserve">
<circle fill="#5B2B6E" cx="48.63" cy="47.125" r="42.75"/>
<g>
    <line fill="none" stroke="#FFFFFF" stroke-width="5" stroke-miterlimit="10" x1="48.85" y1="47.125" x2="26.41" y2="47.125"/>
    <line fill="none" stroke="#FFFFFF" stroke-width="5" stroke-miterlimit="10" x1="70.85" y1="47.125" x2="58.25" y2="47.125"/>
    <polyline fill="none" stroke="#FFFFFF" stroke-width="5" stroke-miterlimit="10" points="44.794,65.51 26.41,47.125 44.794,28.74   
        "/>
</g>
</svg>

I don't know if this would be a good way about doing things, because they behave weird in IE and some browsers, unless I specifically set both width AND height on their parent. Some of the SVGs stretch, some have their heights are all messed up. But in Chrome, everything's good.

What would be the best take on this?

Kenny Bones
  • 5,017
  • 36
  • 111
  • 174

1 Answers1

2

It's better to remove height and width (and x, y and viewBox if needed) attributes from svg itself and use both width and height in css. Ex:

.parent svg {
   width: 100%;
   heigth: 100%;
}

.parent {
   width: 100px;
   height: 50px;
}

Or:

.parent svg {
   width: 100px;
   heigth: 50px;
}

So you can easily make everything responsive.

velocityzen
  • 86
  • 10
  • Ah, I see. It behaves differently when I'm using img tags with the svg as a source. As soon as I embedded the svg directly into the markup, it all behaved like I'd expect :) So basically, it looks like it's not adviced to use svgs as source for img tags. – Kenny Bones Jan 25 '14 at 17:15