Patrick McCaffrey
Patrick McCaffrey

Reputation: 357

How to scale an SVG rectangle while maintaining aspect ratio?

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.

Upvotes: 5

Views: 4164

Answers (2)

Robert Longson
Robert Longson

Reputation: 124049

SVG has a preserveAspectRatio attribute. You stick it on the <svg> element and give it an appropriate value depending on how you want the aspect ratio preserved and it will do everything for you, no javascript required. You'll need a viewBox attribute set too, otherwise preserveAspectRatio is ignored.

Upvotes: 3

Paul LeBeau
Paul LeBeau

Reputation: 101820

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/

Upvotes: 6

Related Questions