I need to apply 'align-items' to the flex container, but when I do, the image disappears.
I have a container that displays flex. And image inside that is in block using ratio 16/9.
I want to apply 'align-items' to .container class and expected the image not to disappear.
.container {
display: flex;
flex-direction: column;
background-color: #abbaea;
width: 500px;
height: 500px;
justify-content: center;
}
.container > div {
background-color: #fbd603;
}
.container > div .aspect-ratio-16-by-9 {
position: relative;
}
.container > div .aspect-ratio-16-by-9 .media {
position: relative;
top: 0;
left: 0;
width: 100%;
}
.container > div .aspect-ratio-16-by-9 > :first-child {
width: auto;
max-width: 100%;
}
.container > div .aspect-ratio-16-by-9 > img {
max-height: 100%;
}
.container > div .aspect-ratio-16-by-9::before {
content: "";
display: block;
padding-bottom: calc(100% / calc(16 / 9));
}
.container > div .aspect-ratio-16-by-9 > :first-child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: auto;
max-height: 100%;
}
<div class='container'>
<div>
<div class="aspect-ratio-16-by-9">
<img class='media' src='https://i.ibb.co/4S4J60N/tree1000-1.png' />
</div>
</div>
</div>
When you apply align-items
to the .container
, it consumes all available space in the horizontal axis and, as a consequence, squeezes the child div to 0 width.
This happens because there is no width defined on the child div.
To fix the problem, add width: 100%
to the child div.
.container {
display: flex;
flex-direction: column;
background-color: #abbaea;
width: 500px;
height: 500px;
justify-content: center;
align-items: center; /* NEW */
}
.container>div {
width: 100%; /* NEW */
background-color: #fbd603;
}
.container>div .aspect-ratio-16-by-9 {
position: relative;
}
.container>div .aspect-ratio-16-by-9 .media {
position: relative;
top: 0;
left: 0;
width: 100%;
}
.container>div .aspect-ratio-16-by-9> :first-child {
width: auto;
max-width: 100%;
}
.container>div .aspect-ratio-16-by-9>img {
max-height: 100%;
}
.container>div .aspect-ratio-16-by-9::before {
content: "";
display: block;
padding-bottom: calc(100% / calc(16 / 9));
}
.container>div .aspect-ratio-16-by-9> :first-child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: auto;
max-height: 100%;
}
<div class='container'>
<div>
<div class="aspect-ratio-16-by-9">
<img class='media' src='https://i.ibb.co/4S4J60N/tree1000-1.png' />
</div>
</div>
</div>