Home > Back-end >  Scale SVG to fill 90% of available space (while maintaining aspect ratio)
Scale SVG to fill 90% of available space (while maintaining aspect ratio)

Time:09-11

I have a <div id="Frame"> element, within it is a <svg> element. I would like the <svg> element to be centered in the frame, and grow at a aspect ratio of 1/1, until one edge uses up say 90% of the available space (so it almost fills the whole space, but has a bit of a border). But I can't get the SVG to grow. I read the many other similar SO answers, some say CSS overrides the width/height attributes of the SVG, but I tried removing them just incase (not ideal), but it still did not grow). The other common soluation is width: 100%; height: auto;, which did not work for me.

main {
  padding: 0; margin: 0;
  width: 100vw;
  height: 100vh;
  }
  
#FRAME {
  padding: 0; margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: lightyellow;
  position:relative;
}

#FRAME svg {
  max-width: 90%;
  max-height: 90%;
  width: 90%;
  height: auto;
  aspect-ratio: 1/1;
  flex-grow: 1;
}
<main>
  <div id="FRAME">
    <svg xmlns="http://www.w3.org/2000/svg" height="24" width="24">
      <path d="M0 0h24v24H0z" fill="none"></path>
      <path d="M3 5v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5a2 2 0 0 0-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z"></path>
    </svg>
  </div>
 </main>

CodePudding user response:

You'll need to add a viewBox to the SVG to determine the SVG viewport.

Whilst the width and height attributes help with keeping the aspect ratio, viewBox helps with scaling the SVG contents correctly.

<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24">
  <path d="M0 0h24v24H0z" fill="none"></path>
  <path d="M3 5v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5a2 2 0 0 0-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z"></path>
</svg>
  • Related