Every example that I have found including what is supposedly the right answer:
Maintain the aspect ratio of a div with CSS - Maintain the aspect ratio of a div with CSS
The problem always is that at some point the box clips (Overflows) usually on the vertical axis.
I am trying to create a responsive box that maintains the aspect ratio in both directions AND NEVER clips(Overflows) in either direction (ie: the aspect ratio box is never larger than 90% of the viewport). I've tried using both height and width as the basis for the calculation but neither works and height seems to be cleaner for my purposes (The height of the images never change but the width will depending on the aspect ratio of the image.
Is it possible to have a box that maintains its aspect ratio and never overflows the viewport?
.demoWrapper {
padding: 1vh;
background: white;
box-sizing: border-box;
resize: both;
border: 1px dashed;
overflow: auto;
max-width: 100%;
height: 80vh;
}
div {
width: 50%;
padding-bottom: 35%;
background: gold; /** <-- For the demo **/
}
<div class="demoWrapper">
<div></div>
</div>
To ensure the box keeps its aspect ratio but never overflows the viewport (which has been specified as width not exceeding 90vw and height not exceeding 90vh) CSS can calculate the best fit:
.box {
display: inline-block;
--ratio: calc( 3 / 2);
/* put the aspect ratio width to height you want */
--h: min(calc(90vw / var(--ratio)), 90vh);
height: var(--h);
width: calc(var(--h) * var(--ratio));
background-color: red;
}
<div class="box"></div>
This assumes the aspect ratio of the box is known.
If not it can be calculated on first load and the CSS variable set, but this requires Javascript. It is unclear from the question whether the aspect ratio is known or not.
If the aspect ratio is set by an image then there may be other ways.