0

I'm loading .svg images into my website using snap.svg (a jQuery plugin from snapsvg.io) this only loads in the image in place where my fallback is and makes certain elements animatable without losing the structure in my html.

The problem I face is that the images will not scale on older browsers (for example IE9, IE10, Safari 6)

The svg properties:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 2100 1174.2" style="enable-background:new 0 0 2100 1174.2;" xml:space="preserve">

When using firebug in BrowserStack I can see that the outer svg element is 100% width, ratio is lost.

Here is a small list of things I tried (some desperate and ridiculous):

  • removing aspect ratio
  • removing the viewBox
  • Adding width (100%)
  • Adding width (100%) and height (auto)
  • Renaming layer id (there are multiple svg images on the same page)

Noteworthy:

  • All path styling is inline (from Illustrator export)
  • All svgs loaded as <img> do work
  • Example from this question does work in older browsers (I took this example as proof that padding-hacking is not necessary)

Thank you in advance

Community
  • 1
  • 1
Mike Duister
  • 260
  • 3
  • 15

1 Answers1

2

The solution has been found!

In older browsers (with these issues) a declaration of height and width is required. Not having one of them results in a default setting (ex. IE9 150px in height)

I solved this issue by writing some JavaScript (jQuery):

function setSvgHeight() {
    $('svg').each(function() {
        var viewBox = $(this).attr('viewBox').split(" ");
        $(this).css("height", (( $(this).parent().width() / viewBox[2] ) * viewBox[3] ));
    });
}

This function loops through all <svg> elements, requests the viewBox and sets the height of the svg to the calculated height (keeping ratio in mind). This works because the width is already defined in css.

$(window).on("resize", function() {
    setSvgHeight();
});

$(window).on("load", function() {
    setSvgHeight();
});

The triggers shown above make sure the aspect ratio keeps the same when resizing. And gives an initial trigger for setting the height.

var interval = setInterval(function(){
    if($('.source').length == 0){
        setSvgHeight();
        clearInterval(interval);
    }
}, 50);

I wrote the interval shown above to count my fallback images, I used a plugin that replaces these fallback images (having the class "fallback") with inline SVG. Once the amount of fallback images reaches 0 it means all are loaded and the function to set the height is triggered.

Mike Duister
  • 260
  • 3
  • 15