This might be a stupid question, but I just started playing with SVG's today, and am running into an issue. I'm not sure if I'm just thinking about it the wrong way, or if I'm trying to do something that's not meant to work.
What I'd like to do, is create an SVG rectangle that has a height that is 30% of its width. I'd like this SVG to scale within a <div>
, but I can't seem to get it to work.
Ideally, I'd like to be able to set a max height and width for the SVG to scale to, as well (1500x450, in this example).
Also, I'm trying not to use JavaScript to get this done.
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.
We use viewBox to make the SVG image scalable. viewBox = “0 0 100 100”: defines a coordinate system having x=0, y=0, width=100 units and height=100 units. Thus, the SVG containing a rectangle having width=50px and height=50px will fill up the height and width of the SVG image, and all the dimensions get scaled equally.
An SVG image with fixed dimensions will be treated just like a raster image of the same size. Note: If you are trying to stretch your SVG to a different aspect ratio with CSS—for example in order to stretch it over the page background—make sure your SVG includes preserveAspectRatio="none" .
In order for SVGs to scale properly, they need to have a viewBox attribute. The viewBox attribute describes the bounds of the content. Without it, a renderer (browser etc) has no way of working out how to scale the SVG to fill the parent.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 30">
<rect x="0" y="0" width="100" height="30" fill="orange" />
</svg>
Demo: http://jsfiddle.net/zApv4/
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