0

In my site (see example at https://jsfiddle.net/xo4m391y/)

body {
  height: 100vh;
}

#parentDiv {
  display: flex;
  height: 100%;
  flex-direction: column;
}

#content {
  display: flex;
  flex: 1;
}

#leftCol {
  flex: 1;
  background-color: blue;
  display: flex;
  position: relative;
}

#rightCol {
  flex: 2;
  background-color: green;
}

img {
  flex: 1 1 auto;
  object-fit: contain;
  max-height: 100%;
  max-width: 100%;
  position: absolute;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div id="parentDiv">
  <nav class="navbar navbar-light bg-primary">
    <span class="navbar-brand mb-0 h1">Navbar</span>
  </nav>
  <div id="content">
    <div id="leftCol">
      <img src="https://wbelajac.files.wordpress.com/2010/02/img_1117a.jpg?w=386&h=600" />
    </div>
    <div id="rightCol">
    </div>
  </div>
</div>

I've used position: relative and position: absolute (Image flex item does not shrink height in a flexbox Flexbox: shrink image to fit) to get the image height to shrink to the size of the container.

This seems like an oddly hackish way of doing this, and eliminates the ability to, e.g., automatically center the image using flexbox. Is there a pure flexbox solution that does not use position: relative and position: absolute to allow the image to shrink?

Additionally, if possible, I'd also like to remove the empty space on the sides of the left div when the view port is small.

Many thanks for any assistance you can provide!

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
ww2406
  • 109
  • 9
  • 1
    add min-height: 0; to `#content` and simply remove position:absolute from the image (probably add object-position: top left; to it too) – Temani Afif Jul 03 '20 at 20:55
  • 1
    otherwise avoid img to be a flex child so you do not have deal with side effects : possible example : https://jsfiddle.net/v2417to3/ (idem for grid display, avoid img to be a direct grid child, so you do not run into these kind of issues , best way to cure a bug/unexpected behavior is not to trigger it ) – G-Cyrillus Jul 03 '20 at 21:05
  • Thank you both--I can't believe it was this simple. I probably spent more time than I should admit on this :D @Temani, any chance you could give me some intuition on why min-height: 0 on #content works? – ww2406 Jul 03 '20 at 21:10
  • (and @G-Cyrillus too, just noticed that in there as well) – ww2406 Jul 03 '20 at 21:15
  • I added a duplicate question detailling this – Temani Afif Jul 03 '20 at 21:25

0 Answers0