How to scale an SVG with <image> tag fallback?

I am examining how to add external SVG files in a responsive manner, and fell for the SVG image tag trick, because it doesn't require JavaScript.

(The SVG has been 'washed' with scour, thus being stripped of height/width attributes, and viewBox being added, as recommended.)

The problem is that this technique seems to require a height and width attribute to work, on the image tag, which isn't responsive. Suggested syntax is:

<svg width="200px" height="100px">
    <image xlink:href="logo.svg" src="logo.png" width="200px" height="100px"/>
</svg> 

However, setting relative dimensions, like so:

<svg style="width:100%; height:100%">
    <image xlink:href="logo.svg" src="logo.png" width="100%" height="100%"/>
</svg> 

.. makes the SVG responsive, however renders the <image> element incorrectly (or, not as expected anyway). This can be fixed by adding preserveAspectRatio and viewBox attributes:

<svg style="width:100%; height:100%" preserveAspectRatio="xMidYMid meet" viewBox="0 0 200 100">
    <image xlink:href="logo.svg" src="logo.png" width="100%" height="100%"/>
</svg> 

Now everything works as expected in all major browsers, except that in IE9-11, the problem now lies with <svg> tag: it's not wrapped around the <image> tag.

Been playing around with various combinations, like omitting the <svg>'s height attribute, but to no avail.

Has anyone solved this without using JavaScript or conditional statements?

Note: Other methods to achieve the same is of course welcome (that is, responsive, external SVG file, working fallback, and without using JavaScript) Note 2: The described method does not fallback gracefully in Safari on IOS 5 either.

Answers


I was working on the same issue today and ran across your question hoping for an answer.

Check out this code for the answer: http://jsfiddle.net/ECTBL/

The trick was having the right attributes in my SVG file i.e.

height="..." 
width="..." 
viewBox="..." 
xml:space="preserve"

When I saved the file from illustrator, it was missing a height and width attributes in the SVG file.

Finally, you'll need the following CSS for it to work:

This is for a bug in webkit

svg { max-height: 100%; }

And of course, this makes the image stretch.

img { width: 100%; }

Need Your Help

Great projects, works, people in intersection of programming and art/music?

flash animation

In a recent question I was introduced to the work of André Michelle, which blew me away. What other great people or works do you know in the fields of art and music? As someone with a love for math/

Custom Json data from Facebook Applinks

android facebook applinks

I am using below piece of code for getting target_url to my App.. every thing works fine but I want to pass json data from the target site to my app.. I have refered to Applinks.org documentation but