Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resize a large svg to fit inside a div

Tags:

I have the following div inside <body>.

<div style="width:320px; height:480px;">     <svg id="svg1"></svg>             </div> 

I want to fit a 640X480 svg inside this div. I have tried this:

var paper=Snap("#svg1"); Snap.load("somesvg.svg",function(f){   paper.append(f);  });   paper.attr({   width:320, height:480  })  

But the svg is cut off from the right size.

like image 754
naheed Avatar asked Jan 14 '14 04:01

naheed


People also ask

How do I make SVG fit inside a div?

Set the CSS attribute position:absolute on your <svg> element to cause it to sit inside and fill your div. (If necessary, also apply left:0; top:0; width:100%; height:100% .)

How do I make SVG fit to the parent container 100?

We use viewBox to make the SVG image scalable. viewBox = “0 0 100 100”: defines a coordinate system having x=0, y=0, width=100 units and height=100 units. Thus, the SVG containing a rectangle having width=50px and height=50px will fill up the height and width of the SVG image, and all the dimensions get scaled equally.


2 Answers

I was wondering about adjusting the viewBox for this, so something like...

<div style="width:320px; height:480px;">     <svg id="svg1" width="100%" height="100%" viewBox="0 0 640 480" preserveAspectRatio="xMaxYMax"></svg> </div> 

jsfiddle http://jsfiddle.net/9zRR8/5/

like image 58
Ian Avatar answered Sep 22 '22 18:09

Ian


The SVG will not scale because it does not have a viewBox defined. The viewBox tells the browser what the dimensions of the content are. Without it, there is no way to determine how much it should be scaled up or down to fit.

This is kind of a failing of svg-edit. It really should be adding one, ideally.

What you could try is loading the SVG into Inkscape or another SVG editor which should add a viewBox. Alternatively, you could add one manually, as per Ian's answer.

like image 30
Paul LeBeau Avatar answered Sep 23 '22 18:09

Paul LeBeau