How to scale SVG proportionally

I exported SVG from Illustrator and would like to set the SVG height and scale the width proportionally.

Here is an 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 set only the height, the width of the SVG is set to 100%.

So far, I have not been able to find a solution that does not require me to set the height and width.

+4
source share
1 answer

Method 1

Set the height with what you want. Then set the width to something much larger than the proportional width. To stop the renderer by automatically reducing the height so that it matches the width.

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

However, by default this will cause the content to be centered to the right, so you will also need to set the appropriate preserveAspectRatio value.

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

Method 2

Set both the height width and the desired height. Set preserveAspectRatio to one using slice and set the overflow parameter 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 embed HTML, a β€œwrong” size may result in a poor layout. Although it should work in standalone situations.

+7
source

All Articles