Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoscaling an SVG embedded in HTML on window resize

Tags:

html

css

svg

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="http://www.w3.org/2000/svg" version="1.1">   <circle cx="100" cy="50" r="40" stroke="black"   stroke-width="2" fill="red"/> </svg> 

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 <div> container, but haven't gotten it working yet.

Any suggestions?

like image 791
Keith Hughitt Avatar asked Feb 21 '12 17:02

Keith Hughitt


1 Answers

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.

like image 144
feeela Avatar answered Sep 23 '22 02:09

feeela