I have a div. I want to enforce its aspect ratio. As long as its set aspect ratio is preserved and my div is neither wider nor higher than the available vertical / horizontal space, I want it to occupy this space to the greatest extend possible.
In other words, assume I want to enforce the aspect ratio of 4:3. Then:
- if the enclosing container is 120px : 120px, then I want my div to have width of 120px, height of 90px and to be vertically centered;
- if the enclosing container is 240px : 120px, then I want my div to instead have width of 160px, height of 120px and to be horizontally centered.
How do I do so?
I tried:
body {
margin: 0;
}
.outer {
height: 100%;
width: 100%;
background-color: black;
position: absolute;
display: flex;
}
.inner {
background-color: white;
aspect-ratio: calc(2 * sqrt(3)) / 3;
margin: auto;
height: 100%;
}
<div class="outer">
<div class="inner"/>
</div>
This appears to work, but only as long as the browser window is not made narrow. If you make the browser window narrow, then .inner
‘s width will overflow available horizontal space, which is unacceptable for me.
It appears this is enforced by height: 100%;
. Trying to preserve both aspect-ratio
and height
the browser will set width
to unacceptably large values. However, height: 100%;
appears necessary, otherwise .inner
will have dimensions of 0x0! If I try to correct this behavior by setting max-width: 100%
and the browser window is narrow, then the browser will ignore aspect-ratio
and instead just set both width and height to the width/height of the enclosing container, which is again unacceptable for me.
Is there any way to do what I need to do?