0

I've got an image (top row) and a caption (bottom row), The image has a max-width of 400px. Both rows are inside a wrapper with a max height of 100vh. As the code is now, the contents of the wrapper will overflow when its constrained by the viewport. Ideally the image should shrink (keeping its aspect ratio) while the caption is still visible at the bottom.

HTML:

<div class="wrapper">
  <picture>
    <img src="https://images.theconversation.com/files/350865/original/file-20200803-24-50u91u.jpg?ixlib=rb-1.1.0&q=45&auto=format&w=1200&h=1200.0&fit=crop" />
  </picture>
  <div class="caption">This is a responsible cat</div>
</div>

CSS:

html, body { height: 100%; }
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background: #202227;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fafafa;
  border: 2px solid pink;
  text-align: center;
}

.wrapper {
  padding: 10px;
  max-height: 100vh;
  background: #37393d;
  border: 5px solid #36badd;
}

img {
  width: 100%;
  max-width: 400px;
}

JSFiddle demo: https://jsfiddle.net/audunolsen/w30e4sgq/17/

Audun Olsen
  • 597
  • 6
  • 17

1 Answers1

1

You're example can't work the way you want it to, because a percentage-based max-height always uses the parent's height, not its max-height (see this answer). Instead, add the max-height: 100vh directly to the image.

Updated fiddle: https://jsfiddle.net/qw70tr2f/1/

MoritzLost
  • 2,611
  • 2
  • 18
  • 32
  • Appreciate the answer. This pushes out the bottom row, however. Could maybe be fixed by using calc, but that means knowing the height of the caption, which is not ideal. – Audun Olsen Feb 19 '21 at 08:54
  • @AudunOlsen You're right, unfortunately this is an "impossible" layout. You either need to know one of the heights (of the wrapper or the image) or set one of the dimensions fixed (either the caption, then you can use calc, or set the wrapper to height: 100vh instead of max-height: 100vh). – MoritzLost Feb 19 '21 at 09:49