Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale SVG proportionally

Tags:

svg

I've exported an SVG from Illustrator and would like to set the height of the SVG and have the width scale proportionally.

Here's the example SVG:

<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="10px" viewBox="0 0 20 10">
        <path fill="#124C92" d="M20,7c0,1.65-1.35,3-3,3H3c-1.65,0-3-1.35-3-3V3c0-1.65,1.35-3,3-3h14c1.65,0,3,1.35,3,3V7z" />
</svg>

If I only set the height, the SVG width is set to 100%.

So far I've been unable to find a solution that doesn't require me to set both the height and width.

like image 715
Ben Foster Avatar asked Oct 25 '13 11:10

Ben Foster


1 Answers

Method 1

Set the height to what you want. Then set the width to something much greater than the proportional width would ever be. That's to stop the renderer automatically reducing the height to fit the width.

<svg height="100px" width="1000px" ... >

However, by default, that will cause the content to be centred way off to the right, so you will also need to set a suitable preserveAspectRatio value.

<svg height="100px" width="1000px" preserveAspectRatio="xMinYMin" ... >

Method 2

Set both the height an width to the desired height. Set the preserveAspectRatio to one with slice and set the overflow to visible.

<svg height="100px" width="100px" preserveAspectRatio="xMinYMin slice" overflow="visible" ... >

This approach may not be suitable for some situations. For example, if you are embedding in HTML, the 'incorrect' size may result in the layout being wrong. Though it should work for standalone situations.

like image 74
Paul LeBeau Avatar answered Oct 19 '22 01:10

Paul LeBeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!