Scale inline SVG images inside HTML documents

Let’s say your designer created a beautiful SVG vector image that you want to be able to use inline in your HTML – but it’s the wrong size for where you want to use it on the page. Perhaps you need to scale it down (or up!). Here’s the easiest, fastest way to do so – without using CSS:

First, make sure your SVG uses width, height and viewBox parameters:

<svg xmlns="http://www.w3.org/2000/svg" width="116" height="184" viewBox="0 0 116 184" version="1.2">

If you don’t have a viewBox, you can add one like the example above – set the value as 0 0 width height, with all values in pixels. Similarly, if you don’t have width or height – create it from the viewBox.

Next, work out what the revised width and height of the scaled image are. An easy option for this is the Image resizing and aspect ratio calculator over at Red Route – just remember to round any decimal places in the new width and height values.

Finally – update the width and height parameters, leave the viewBox parameter at the original values, and add a preserveAspectRatio parameter – per the following example:

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="40" viewBox="0 0 116 184" preserveAspectRatio="xMidYMid" version="1.2">

More documentation on the preserveAspectRatio parameter is available at MDN Web Docs.

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *

29 − = 23

This site uses Akismet to reduce spam. Learn how your comment data is processed.