0

I would like to display an svg image inside a block of fixed size. I would like to show the image undistorted and as large as possible within the block. My problem is that the image is supplied by the user, so I do not know its dimensions. Is there any way to do this with CSS only?

Eduardo
  • 8,362
  • 6
  • 38
  • 72
  • why not detect its dimensions? There is a method for getting the bBox of any SVG element through the browser SVG implementation http://www.w3.org/TR/SVG/types.html#__svg__SVGLocatable__getBBox – nicholaswmin Apr 22 '14 at 17:44
  • @NicholasKyriakides: I can do that, but I was wondering if there was a way to do it without Javascript. – Eduardo Apr 22 '14 at 17:47
  • Is this relevant to what you are looking for? http://stackoverflow.com/questions/8919076/how-to-make-a-svg-element-expand-or-contract-to-its-parent-container – nicholaswmin Apr 22 '14 at 17:49
  • @NicholasKyriakides: I saw that one, but it is not what I'm looking for. That fixes the two dimensions. In my case, I would have to fix the largest one only: height if the svg is taller than wider, width if it is the other way around. I was wondering if there was a CSS way to "scale to best fit". – Eduardo Apr 22 '14 at 18:06
  • I'll leave this post since I'm not too sure I can answer but I have a feeling this won't be possible without JS. Good luck. – nicholaswmin Apr 22 '14 at 18:12
  • if SVG has the attribut viewbox it should scaled keeping it's own ratio.then add max-height or max-width if needed, best is you provide a jsfiddle or codepen example close to your reality. – G-Cyrillus Apr 22 '14 at 18:50

1 Answers1

4

No you cannot do this using CSS only. The attributes that tell the browser how to scale an SVG to fill its parent container are defined in the SVG itself. There are four attributes in particular that control the scaling:

  1. width
  2. height
  3. viewBox
  4. preserveAspectRatio

The first two can be overridden with CSS, but the last two cannot. If you have no control over the SVG, then you can't guarantee that it has a viewBox or preserveAspectRatio.

You could, however, manipulate the viewBox and preserveAspectRatio attributes with Javascript.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181