How to scale an SVG with tag fallback?

2019-08-07 10:29发布

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.

1条回答
时光不老,我们不散
2楼-- · 2019-08-07 10:46

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%; }
查看更多
登录 后发表回答