jonhobbs jonhobbs - 28 days ago 5
CSS Question

height: auto on SVG not working

I am trying to use an SVG sprite sheet using the "symbol" method detailed here.

My HTML is very simple.

<svg><use xlink:href="/images/iconSprite.svg#camera"/></svg>

And here is an example symbol from the SVG file

<symbol viewBox="0 0 24 24" id="clock"><g transform="translate(0 -1028.4)"><path d="M22.085 1035.955a10.997 10.997-23.5 1 1-20.17 8.77 10.997 10.997-23.5 1 1 20.17-8.77z" fill="#1abc9c"/><path d="M21 1040.335a9 9 0 1 1-18 0 9 9 0 1 1 18 0z" fill="#ecf0f1"/><path d="M1.034 1039.8c-.083 1.7.176 3.3.875 4.9 2.42 5.6 8.898 8.2 14.468 5.8 4.29-1.9 6.778-6.2 6.593-10.6-.202 4-2.63 7.8-6.592 9.6-5.57 2.4-12.047-.2-14.47-5.8-.556-1.2-.82-2.6-.874-3.9z" fill="#16a085"/><path d="M20 1040.4c0 .5-.448 1-1 1h-6v-2h6c.552 0 1 .4 1 1z" fill="#3498db"/><path d="M12 1033.4c-.552 0-1 .448-1 1v5h2v-5c0-.552-.448-1-1-1z" fill="#2c3e50"/><path fill="#c0392b" d="M6.017 1045.705l4.95-4.95.707.707-4.95 4.95z"/><path d="M12 1038.4c-1.105 0-2 .9-2 2s.895 2 2 2 2-.9 2-2-.895-2-2-2zm0 1c.552 0 1 .4 1 1 0 .5-.448 1-1 1s-1-.5-1-1c0-.6.448-1 1-1z" fill="#34495e"/></g></symbol>

THe problem I am having is that when I use CSS to set the width of the SVG element to 64px the height of the SVG is automatically set to 150 pixels. I have tried setting height:auto; and height:100%; on the SVG element but it makes no difference. The only way to get it to work is to set height:64px; which I don't want to do because the aspect ratio of my icons may not always be square. What I want it to do is automatically scale the SVG in its original aspect ratio, so a 4:3 icon (as defined by the viewbox) would automatically get a heightof 300px if I set the width to 400px.

I have read several guides on scaling SVG and preserving aspect ratio and some have solutions when using an IMG element but I can't find one for inline SVGS, or using an external SVG with USE.

Anybody know a solution which works in all browsers including IE9+ and Android 4.0+?



You need to define a viewBox on each element that you link to. because there can be different elements in one SVG document.

So remove the viewBox from the element you link to. Add a viewBox to the place you're linking from.

I suggest you add the viewBox to a svg element:

<svg class="test" viewBox="0 0 25 25">
    <use xlink:href="/images/iconSprite.svg#clock"/>

Now you can scale it:

If you define the css width:

.test {
    width: 50px;

It will display as long as it fits on height or width.

So if you want a responsive design you can simply scale it by % length
.test { width:30%; }

SCALE SVG A really good article about scaling svg from CSS-tricks :)