12

Does anyone know I can dynamically resize an svg image so it fits within a container?? I find that the images I have overflows. What I want is a way to resize it so it doesn't overflow. Any response is appreciated. I have also tried setting the width and the height to 100%

k.ken
  • 4,973
  • 5
  • 23
  • 21

2 Answers2

15

Okay, so the easiest way of doing dynamic widths is just to provide a percentage value for width or/and height. You can find my example in a fiddle here http://jsfiddle.net/VDKwy/

So the key part is either leaving out the width and height properties of off the svg element, or

<svg width="100%" height="100%"></svg>

And then using percentage value for inner elements like so:

<rect x="10%" y="10%" width="80%" height="80%" style="fill:blue;stroke-width:5; stroke:black" />
Morgan Wilde
  • 16,795
  • 10
  • 53
  • 99
  • This is an example of how my container looks. The expressions image is an svg. Here is a link to a snapshot of it: http://imgur.com/3Yw6v – k.ken Nov 04 '12 at 16:09
  • So if you provide dynamic width&height on that it's not fitting you required space? – Morgan Wilde Nov 04 '12 at 16:14
  • So you need to provide dynamic values for your container div and your inside elements of the svg container. Either way it's super difficult to understand why it overflows from just an image. – Morgan Wilde Nov 04 '12 at 16:18
  • yeah I understand. I thought another option will be available – k.ken Nov 04 '12 at 16:27
  • @k.ken well you're dealing with Scalable Vector Graphics, so you shouldn't feel this option of dynamic width/heights is something to be avoided. Your image is going to scale and look as good if you shrink it or increase it's size. – Morgan Wilde Nov 04 '12 at 16:33
  • I have tried every possible solution I find. It's a frustrating. Would you like a closer look at my code? – k.ken Nov 04 '12 at 16:59
  • @k.ken, sure it'd be interesting to see, post it in a fiddle somewhere and send me a link wilde.morgan@gmail.com – Morgan Wilde Nov 04 '12 at 17:40
  • I generated svg from Graphviz dot. Copying the svg content to my xwiki page and simply change the size using `` works for me. – panc May 01 '20 at 16:42
  • @MorganWilde nice in theory. In practice small svgs can look blurry and common advice seems to be to resize them to match the render size. – geotheory Feb 17 '21 at 20:35
0

I found it easier to remove the width and the height attributes and apply pixel dimensions from a wrapper div, e.g.

<div style="width: 48px; height: 48px;">
  <svg xmlns="..." viewBox="..."></svg>
</div>

Radi Totev
  • 91
  • 7