1

I have a grid of images which are to display in a single row. The grid's height is not to exceed the height of the browser. Each image can my any height and any width.

The image must be vertically and horizontally centered in its container. If the image's height or width is bigger than its container, then the image should not overflow its bounds.

Is this possible?

There are many posts out there asking similar questions.

Constrain img to div and maintain aspect ratio?

CSS: How can I set image size relative to parent height?

And so on. However none that I see are using flexbox.

<div class='grid-container'>
  <div class='grid'>
    <div class='col'>
      <div class='img-container'>
        <img src='http://via.placeholder.com/300x150'/>
      </div>
    </div>
    <div class='col'>
      <div class='img-container'>
        <img src='http://via.placeholder.com/200x400'/>
      </div>
    </div>
  </div>
</div>

https://codepen.io/stljeff1/pen/MEWoPN

Here is a codepen showing what I'm trying to do

Why does img {max-height: 100%; } not do anything but img { height: 150px; } constrains the image?

**********Edit**************** as pointed out in comments below, I could use object-fit. The example cited Works in IE Edge, not IE 11.

Jeff Wilkerson
  • 376
  • 2
  • 18
  • height:100% needs a parent with a valid height. the cascad to inherit a valid height value to be calculated is lost from .grid which has no height. 100% of what ? parent container set at 200px or the window ? to inherit height + object-fit , you could have this https://codepen.io/anon/pen/WZNEYQ or https://codepen.io/anon/pen/JrjyVv – G-Cyrillus Sep 12 '17 at 21:39
  • yes, i did come across object-fit. is that cross browser compatible? I thought it broke in IE. There are polyfills, however, i'd like to avoid if possible. – Jeff Wilkerson Sep 12 '17 at 21:41
  • okay, do you want to use flex or any other display ? what is the maximum height you refer to : 200px or window's ? – G-Cyrillus Sep 12 '17 at 21:50
  • max height is window, or a little less for padding – Jeff Wilkerson Sep 12 '17 at 21:53
  • 1
    then you can use max-height:100vh only on img tag, and let the parent do their regular job without mastering heights. https://codepen.io/gc-nomade/pen/ZXEXGX ;) It works with IE11 – G-Cyrillus Sep 12 '17 at 21:57
  • Thats great. Perfect. The answer, then, is that the only way to get an image to constrain itself is to apply a max height that is fixed. Percentages are relative, not fixed. Using the Viewport height is fixed. – Jeff Wilkerson Sep 12 '17 at 22:08

1 Answers1

0

I dunno if you try to do this :

    img {
      width: 100%;
      max-height: 100%;
      display: block;
    }

https://codepen.io/headmax/pen/wrvqRv