Home > Enterprise >  Why SVG resizes to width but not to height?
Why SVG resizes to width but not to height?

Time:12-02

I'm trying to understand why my SVG will resize when I change the width of its parent but it won't resize when I change the height.

I just made a very simple jsFiddle. You can try resizing the little window at the bottom right corner.

From what I understand, it's key that the parent has 100% width and height so that a window resize is detected and inner svg can adjust. It's also key to specify the viewBox attribute to allow the svg to resize according to its parent div.

But why is it not resizing accorindg to height?

div {
  height: 100%;
  width: 100%;
}
<div>
  <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="100" />
  </svg>
</div>

http://jsfiddle.net/7dz60fkh/

CodePudding user response:

SVGs are way more different than pixel images such as jpeg, png ..etc. The hard part is that you shouldn't think of them like you would with "normal" images, to make things short SVG aren't IMAGES but DOCUMENTS that contains info.

When you include an HTML file with an , you don’t expect the text inside to scale when you change the size of the frame. Same with SVG. By default, it will be drawn at the size specified in the code, regardless of the size of the canvas.

If your svg has something called a viewbox ( which is your case ) then it will be scaled to fit it's defined viewport so increasing the height of the img won't make the icons any taller. You'll just end up with the img in a wider box.

I think mainly your problem is that your SVG have fixed values defined in them. Open up the SVG files and make sure they either: have no width and height defined, OR have width and height both set to "100%".

you can read more about SVGs in this article, it'll help you understand how things work hopefully

CodePudding user response:

You need to give the html, body and svg elements the same percentage sizes too so they all resize in lock step.

div, html, body, svg {
  height: 100%;
  width: 100%;
}
<div>
  <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="100" />
  </svg>
</div>

  • Related