| Posted under Articles

How to make an SVG Resizable

Recently, i wanted to place an SVG inside my html, but i needed it to resize in order to fit any screen.

I also wanted to avoid changing both its width and height in various breakpoints as this would not be a viable solution.
Surprisingly, the answer was very simple: All you have to do is get rid of the height attribute and replace it with

preserveAspectRatio="xMinYMin meet"

So for example the following SVG

<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
   <path d="M0 0h24v24H0z" fill="none"/>
   <path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/>
</svg>

would turn into

<svg fill="#000000" viewBox="0 0 24 24" width="24" preserveAspectRatio="xMinYMin meet" xmlns="http://www.w3.org/2000/svg">
   <path d="M0 0h24v24H0z" fill="none"/>
   <path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/>
</svg>

Now in our CSS we can only set the width for the above SVG.

Thanks for your likes, this will motivate me to write posts more often!