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?
Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.
To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect ...
Set the CSS attribute position:absolute on your <svg> element to cause it to sit inside and fill your div. (If necessary, also apply left:0; top:0; width:100%; height:100% .)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With