Feedfedfat
Feedfedfat

Reputation: 193

How to make an svg element responsive to it's parent container?

I'm trying to acheive this:
Rendering an svg square (w:h = 1:1 rectangular) inside of div, when the div's width is greater than height, the square should fit into the container by the height(red box is the div, green box is the svg square):
enter image description here

When the div's height is greater than width, the squire should fit into the container by the width:
enter image description here

It can be easily achieved by specifying the size of the svg view port.But if I remove the size of the svg view port, instead when I add the size to the parent div(red box), it refuses to look at the height of the container, the image turns to be: enter image description here enter image description here

Is there a way we can make the square responsive to the container height? here is my code:

#main {
  width: 400px;
  height: 100px;
  border: 4px solid red;
}
<div id="main">
  <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid Meet">
    <rect x="0" y="0" width="100" height="100" fill="green"/>
  </svg>
</div>

Upvotes: 5

Views: 9116

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101956

Just set the width and height attributes of the SVG to "100%". Either in the SVG, or via CSS.

Secondly, fix your other attributes:

  • viewBox values should not have commas.
  • it is preserveAspectRatio, not preserveAspect, and meet, not Meet

#main {
  width: 400px;
  height: 100px;
  border: 4px solid red;
}
<div id="main">
  <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
    <rect x="0" y="0" width="100" height="100" fill="green"/>
  </svg>
</div>

Upvotes: 9

Related Questions