0

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 flexto ì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.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
TFLLL
  • 26
  • 3
  • add `min-height: 0; object-fit: contain;` to image and remove margin from body – Temani Afif Oct 05 '20 at 19:37
  • Huges thanks, it works! Could you explain a bit why this specific solution works (especially the need of `min-height: 0`), and why what I came with first is not cross-browser consistent? Anyway, thanks again! – TFLLL Oct 05 '20 at 19:49
  • I added a duplicate explaining this – Temani Afif Oct 05 '20 at 19:51

0 Answers0