This is easily achieved with only HTML and CSS
I attached a CodePen reference. View here
You will need 3 boxes
<div class="wrapper">
<div class="ratio-box">
<div class="content">I am a div that mantains its aspect ratio</div>
</div>
</div>
The wrapper box has a defined width, which is your element's width":
.wrapper {
width: 200px;
}
.ratio-box {
width: 100%;
padding-bottom: 50%;
position: relative;
}
.content {
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
}
This works because the padding-bottom
property is relative to the width
property of its parent element.
Want a specific aspect ratio?
For a 2:1 aspect ratio, use padding-bottom: 50%;
For a 16:9 aspect ratio, use padding-bottom: 56.25%;
For a 9:16 smartphone aspect ratio, use padding-bottom: 177.78%;