Keith Hughitt Keith Hughitt - 7 months ago 16
CSS Question

Autoscaling an SVG embedded in HTML on window resize

I would like to embed some SVG in an HTML page in a way such that is is automatically resized (using SVG, CSS, or JS) when the page is resized, while still preserving the original aspect ratio.

For example, using an example from W3Schools:

<svg xmlns="" version="1.1">
<circle cx="100" cy="50" r="40" stroke="black"
stroke-width="2" fill="red"/>

Is it possible to set the SVG width = 5% of the window width, and have the height scaled proportionately?

I've tried a couple things including
preserveAspectRatio="xMinYMin meet"
and setting the dimensions to 100% within a
container, but haven't gotten it working yet.

Any suggestions?


You need a viewBox-attribute on your SVG root element, which will define the overall size of the SVG-image:

<svg version="1.1" viewBox="0 0 300 185">

Now you can set the width OR height of the image via CSS and it will scale perfectly.