Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross browser SVG preserveAspectRatio

Tags:

I'm trying to have a SVG graphic inside an <img /> tag that would fit (without crop) inside the tag with preserved aspect ratio. I created the SVG in Inkscape. It worked as expected on all browsers except for Internet Explorer 9.

To make it work on IE 9 I had to add the viewBox="0 0 580 220" and preserveAspectRatio="xMidYMid meet" and remove the width="580" and height="220" SVG properties.

<svg viewBox="0 0 580 220" preserveAspectRatio="xMidYMid meet">...</svg> 

This seemed to work everywhere, just until I tried it on Webkit, where the <img /> tag gets stretched vertically although the aspect ratio of the SVG is indeed preserved.

When I put back the width="580" and height="220" properties, it works on Webkit but on IE 9 the aspectr ratio is lost.

Is there a cross browser solution for this behavior?

like image 559
Peter Hudec Avatar asked May 08 '13 10:05

Peter Hudec


People also ask

What is preserveAspectRatio in SVG?

The preserveAspectRatio attribute indicates how an element with a viewBox providing a given aspect ratio must fit into a viewport with a different aspect ratio.

Can you change SVG viewBox with CSS?

In order to change the value of the SVG viewport's width and height, we can use CSS. Simple. But to change the value of the viewBox , we currently need to use JavaScript. Not all SVG presentation attributes are available as CSS properties; only the set of attributes that have CSS property equivalents can be set in CSS.


1 Answers

Seems like I found the solution:

You need to keep the width and height properties in the SVG.

<svg     width="580"     height="220"     viewBox="0 0 580 220"     preserveAspectRatio="xMidYMid meet" >...</svg> 

And to make it work on IE 9 you need to specify at least one dimension of the <img /> tag.

<img src="your.svg" style="width: 100%" /> 

This seems to be working everywhere.

like image 63
Peter Hudec Avatar answered Sep 24 '22 05:09

Peter Hudec