I'm attempting to achieve the following:
Displaying an SVG square (with a 1:1 aspect ratio) inside a div element. When the width of the div is greater than its height, the square should adjust to fit within the container based on the height (red box represents the div, green box represents the svg square):
https://i.sstatic.net/GMxYw.png
When the height of the div is greater than the width, the square should adjust to fit within the container based on the width:
https://i.sstatic.net/fnWS4.png
This can be easily achieved by specifying the size of the svg view port. However, if I remove the size of the svg view port and instead add the size to the parent div (red box), it fails to consider the height of the container, resulting in the following image: https://i.sstatic.net/agINk.png https://i.sstatic.net/YoCTt.png
Is there a way to make the square responsive to the container height? Below 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>