Take a look at the following code:
#wrapper{
/*set the size of the box*/
width:40%;
margin:0 auto 20px;
}
#ratio{
/*parent is a 16:9 DIV*/
padding-top:56.25%;
position:relative;
background:aqua;
}
img{
display:block;
max-width:100%;
max-height:100%;
/*the fun part: vertically+horizontally center it*/
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
<div id="wrapper">
<div id="ratio">
<img src="https://via.placeholder.com/350x150">
</div>
</div>
<div id="wrapper">
<div id="ratio">
<img src="https://via.placeholder.com/150x350">
</div>
</div>
As you can see, the DIV has a dynamic width and height, which makes it hard to deal with. On browsers like firefox and chrome, you can clearly see a 0 to 1 pixel gap when resizing a certain way. I feel like I tried everything (been troubleshooting this for days at this point).
Any tips or alternatives? I'd rather have a pure CSS solution but javascript ones are also welcome.