I'm trying to create a fixed aspect ratio box that resizes to not overflow its parent.
The classic padding-bottom trick is only able to define height in terms of parent width, and as testable here allows the element to grow taller than the parent as width increases. Not good.
Using vh and vw however, we can accomplish what we want with the restriction that the parent is the dimensions of the viewport. Testable here.
<style>
div {
max-width: 90vw;
max-height: 90vh;
height: 50.625vw; /* height defined in terms of parent width (90*9/16) */
width: 160vh; /* width defined in terms of parent height, which is missing from the padding-bottom trick (90*16/9) */
background: linear-gradient(to right, gray, black, gray);
}
</style>
<div></div>
Is there a way to have a vh and vw equivalent that references the parent instead of the viewport? Or is there a complimentary trick to the padding-bottom trick which fixes its problems? Where is the css ratio property?
Also, images have some sort of intrinsic ratio, but I'm unsure how to take advantage of this.