Displaying an SVG image coherently in all decent Browsers
Dec 16, 2010 20:37 · 454 words · 3 minutes read
As you may have noticed (unless you are using IE), I have a little SVG image at the top right of the page. It was basically an experiment on how SVG can be embedded nowadays. It worked pretty well in opera and firefox but chrome just refused to display it in another size than 300x150 pixels. So what I was looking for was a way to simply embed an SVG image and control it’s size properly so all decent Browser display it correctly.
The final result that did the trick was the following:
- Make sure the SVG only specifies a viewport, but no width and height, make sure the aspect is preserved like so:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 1024 768"
preserveAspectRatio="xMidYMid meet">
- Use the
<object>
tag to embed the image (not<img>
), set the width and height of the object to100%
:
<object height="100%" width="100%"
data="/path/to/your/image.svg" type="image/svg+xml">
<!-- put content for old browsers or IE here, it
will get displayed instead of the SVG. You can
embed a raster version of the image here, but remember it
will get loaded by the SVG capable browsers as well,
even if they don't display it! That may slow your
page down significantly. -->
</object>
- Wrap the object in a div with which you control the actual size. You should be able to use absolute & relative sizes. I use
em
like so:
<div style="width:10em;height:5em">
<object ....
</object>
</div>
Arriving at a working solution was mainly a lot of trial and error. I got the final hints to make it work from this blog post. What was still missing there was setting the <object>
tags width and height to 100%
. That was what finally convinced chrome not to use it’s default size for SVGs (300x150px). I also have not found any definite sources on how the SVGs intrinsic size (i.e. the width
and height
that may or may not be specified in the SVG file itself) plays together with the embedding tag’s size in each browser. The tests I did on that were not conclusive. Absolute pixels were heeded for the image itself, but chrome for example still put it into a 300x150 px frame while Firefox displayed it without cropping or scrollbars. Not defining a size at all and simply defining a viewport made all browsers happy.
The above method worked for me in Opera 11 (though probably Opera 9 & 10 should be OK as well), Chromium 8 and Firefox 3.5. Epiphany 2.3 also displayed the image in the correct size, but does not handle SVG transparancy. (This seems to be the case with all older WebKit based browsers). As Safari also uses WebKit, I hope it also works with this embedding technique.