SVG scaling problem for IE9+

The issue: SVGs don't preserve their aspect ratio in IE

2015-07-23

Let's start with a basic SVG created from sketch:

<img src="img/1in3.svg" alt="">

(internal SVG settings are width="179px" height="105px")

Now, let's use css to apply max-width: 90px

<img src="img/1in3.svg" alt="" style="max-width:90px;">

If you view this page with IE you'll notice the height didn't auto-adjust when we changed the width. We expect images to do that on the web, but this is more than an image...it's SVG.

Screen capture with IE

Screen capture with Chrome

Things to know which help:

  • There are multiple ways to use SVG images on a webpage. I'm referring to the <img> method because it's simple and more like normal images. You'll find that there at lots of different ways to display SVG files on a webpage.
  • The SVG file itself can be opened with a text editor. There are important settings in there which play a role in how the SVG file will scale. That is where attributes like height, width, viewbox, and preserveAspectRatio are.

The fix:

I'm leaning towards the solution found at https://gist.github.com/larrybotha/7881691. It took me awhile to understand what it was talking about because I didn't know the lingo.

Basically, the suggestion is:

  • Step 1: Edit your SVG file to remove the hard-coded height and width attributes. (with simple text editor)
  • Step 2: Apply width:100% css to your svg image to make IE display it like other browsers. (as big as it's container)
  • Step 3: Use css on your image container for consistent results!



Step 1: [details] Edit your SVG file to remove the hard-coded height and width attributes.

That will make the default size go one of two likely ways:

  1. Non-IE browsers will scale it a large as it's container. (that can be huge)
  2. IE browsers will scale it to an arbitraty size that is predetermined for SVG files (300x150)

Example SVG with internal height/width removed: (view in IE vs. other browser)

<img src="img/1in3-noHeightWidth.svg" alt="">



Step 2: [details] Make IE scale like everyone else by applying a width:100% css to the img tag.

<img src="img/1in3-noHeightWidth.svg" alt="" style="width:100%;">


Step 3: [details] Now you can contain the image with something which will be consistent across browsers.

For example, inside a div with css width:450px applied

<div style="width:450px;">
  <img src="img/1in3-noHeightWidth.svg" alt="" style="width:100%;">
</div>


Yay! Now we can go back to SVG goodness even with IE. :)




PS: For browsers that don't support SVG (IE8), I use the .png fallback technique.

<div style="width:450px;">
  <img src="img/1in3-noHeightWidth.svg" onerror="this.src='img/1in3-noHeightWidth.png';this.onerror=null;" alt="" style="width:100%;">
</div>