Is is possible to scale inline SVG with CSS?
CssSvgCss Problem Overview
I want to use CSS styles to control the size of SVG designs. For example...
.svg { width:100%; }
When I embed an SVG image from a file it acts just like any other image and works fine:
<img src="image.svg" class="svg" />
But when I use inline SVG it DOESN't work:
<svg class="svg">...</svg>
The svg "box" will grow, but the contents stay the same.
Is there a way to do this?
Css Solutions
Solution 1 - Css
The first and probably best method you could use is just using the viewBox
attribute (this attribute is case sensitive). That will make the contents of the svg tag automatically take up the defined width and height of the svg tag itself, by only showing what's within the defined boundaries. For example:
<svg width="82" height="82" viewBox="0 0 102 102">
<rect x="1" y="1" width="100" height="100" stroke="black" stroke-width="2" fill="white"/>
<text fill="black" x="10" y="30">FooBarBaz</text>
</svg>
Alternatively, you could apply a svg transform
to the contents of the SVG tag, which would look like this:
<svg width="82" height="82">
<g transform="scale(0.8)">
<rect x="1" y="1" width="100" height="100" stroke="black" stroke-width="2" fill="white"/>
<text fill="black" x="10" y="30">FooBarBaz</text>
</g>
</svg>
Finally, you can try using CSS3 transform
to scale the whole svg element. This is the least supported method, but I mention it anyway because you originally asked for a CSS solution. I strongly suggest using one of the above solutions though, if that's possible at all.
<svg width="102" height="102" style="transform:scale(0.8); -webkit-transform:scale(0.8); -moz-transform:scale(0.8); -ms-transform:scale(0.8); -o-transform:scale(0.8);">
<rect x="1" y="1" width="100" height="100" stroke="black" stroke-width="2" fill="white"/>
<text fill="black" x="10" y="30">FooBarBaz</text>
</svg>