I’m trying to create an empty div that expands to it’s available space using flex: 1
or flex-grow: 1
but keep an aspect ratio using aspect-ratio: 16/9
I’ve tried lots of examples including the original padding-top: 56.25%
hacks. But can’t get anything to work correctly.
Here’s what I have so far:
.parent {
display: flex;
column-gap: 30px;
row-gap: 30px;
}
.container {
display: flex;
background:pink;
flex-direction: column;
height: 300px;
width: 500px;
align-items: center;
justify-content: space-between;
}
#container-2 {
height: 500px;
width: 300px;
background: green;
}
.item {
position: relative;
flex: 1;
background: black;
aspect-ratio: 16/9;
opacity: 0.5;
/* max-width: 100%; */ /* doesn't fix with ratio */
}
<div class="parent">
<div class="container">
<p>Example 1</p>
<div class="item"></div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia incidunt dolorem quam! Tenetur facere, facilis modi ipsa sapiente repellendus dolores doloremque quae. Laborum sapiente voluptatum unde fugit tenetur laudantium animi.</p>
</div>
<div class="container" id="container-2">
<p>Example 2</p>
<div class="item"></div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia incidunt dolorem quam! Tenetur facere, facilis modi ipsa sapiente repellendus dolores doloremque quae. Laborum sapiente voluptatum unde fugit tenetur laudantium animi.</p>
</div>
</div>
You’ll see that the Example 1 works but Example 2 the .item
overflows the width to try and get the aspect ratio with the height. I’ve tried max-width: 100%
which stops the overflow but then the item is not 16:9.
Desired output:
2
Answers
For what it’s worth, I also could not figure this out, but did eventually find this post, which I mostly stole to make the snippet below.
Based on your desired results images, I’d suggest something like this:
Not hugely sophisticated but seems like the height is the deciding factor here as this determines the length of the content, and not the width. So I chose a fixed height that fit the content and then set the width to auto. The aspect ratio stayed the same when I changed the height.
I assume from your desired results images that you want an image inside the div so I added a placeholder as well.
I put two of the divs with this aspect ratio next to each other as I am not quite sure what you are going for, but maybe you can continue to play around with it. It’s already semi-responsive but needs tweaking.