I know the question "How do I auto-resize an image to fit a 'div' container?" has been asked hundreds of times but my problem is slightly different. I have a solution for Firefox but it does not work in Chrome or Safari, and I can't track where the issue come from.
What I want:
- both the image and the caption fully visible and centered
- with the caption just below the image.
- Both image and caption are variable in size.
- Working the same way in Firefox, Chrome and Safari
The below example works in Firefox (even with absolutely no css for img
), but not in Chrome or Safari, where the image doesn't resize when the window's height changes.
.display {
width: 100vw;
height: 100vh;
background-color: #bbf;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.caption {
background-color: black;
color: white;
width: 100%;
text-align: right;
padding: 10px;
box-sizing: border-box;
}
img {
max-width: 100%;
height: auto;
}
<div class="display">
<img src="https://via.placeholder.com/800x400" alt="">
<div class="caption">
<p>Some text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text ome text Some text </p>
</div>
</div>
On the left: Chrome (does not work as expected when height is too small)
On the right: Firefox (work as expected all the time)
window aspect ratio larger than the image: only firefow resizes the image correctly
window aspect ratio taller than the image: both chrome and firefow work as expected
I tried several things, playing with width
, max-with
, margin: auto
, object-fit: contain
, display: block
, using a container div, change flex
to ìnline-flex`, but every time, either the image simply does not resize when the height changes, or the caption is "ignored" and you need to scroll to see it, which I don't want to.
My guess is an issue with how flexbox is handeld by different browsers but all I can find is outdated topics.