Search code examples
csssvgresizescaleinline-svg

How to scale resize SVG contents proportionally, using only CSSs?


How can I scale or resize inline SVG vector artwork, using only CSS, so all artworks resize proportionally and fit fully into their defined width & height?

The original aspect-ratio should be respected.

In this case I would like the artwork contents to resize to 100x100px box as icons. The below snippet doesnt work, since it just seems to CROP the window instead of resizing the inner contents.

svg {
  width:  100px;
  height: 100px;
  fill:   blue;
  background-color: red;
}
<svg>
    <polygon points="100,0 30,200 200,70 0,70 170,200"/>
</svg>

<svg >
    <polygon points="0,0 200,140 110,200"/>
</svg>

<svg>
    <ellipse cx="200" cy="70" rx="200" ry="40" />
</svg>

I'm gtting this: (looks more like a crop)
enter image description here

But I would like to get this: (proportionally scaled to the edge of the box)
enter image description here


Solution

  • Add viewBox to keep the aspect ratio and set 100% height and width to fill the svg container.

    svg{
      width:100px;
      height:100px;
      background-color: red;
    }
    svg * {
      width:  100%;
      height: 100%;
      fill:   blue;
    }
    <svg viewbox="0 0 200 200">
      <polygon points="100,0 30,200 200,70 0,70 170,200"/>
    </svg>
    
    <svg viewbox="0 0 200 200">
      <polygon points="0,0 200,140 110,200"/>
    </svg>
    
    <svg viewbox="0 0 400 70">
      <ellipse cx="200" cy="70" rx="200" ry="40" />
    </svg>