Based on this answer, I try to shrink/grow a flex-item img
element to the height of its sibling. The height gets adjusted correctly, and the image is shrunk correctly - respecting the aspect ratio - but the img
element still consumes as much width as it would without shrinking it (look at the whitespace):
main {
display: flex;
}
section {
display: flex;
flex-direction: column;
border: thin solid black;
}
img {
flex-basis: 0px;
flex-grow: 1;
object-fit: contain;
overflow-y: auto;
}
<main>
<section>
<img src="http://via.placeholder.com/200x200">
</section>
<section>
<div>Match my height.</div>
</section>
</main>
Actual output, in case browsers (will) render the above snippet differently (in the future):
Expected output:
I also tried to set overflow-x: auto;
or width: 100%
(on img
), but it did not make any difference. Is there a way to get the expected shrunk image dimensions in this flexbox layout?
There are many similar questions, but they don't offer the above flexbox solution. Just to name some:
- Grow/Shrink flex item to fit image
- How do I set a flex-item's height to the same height as it's sibling
- Make flex item siblings the same height
- How to set flex item height equally [duplicate]
So, there are alternatives if there is no flexbox solution...