Search code examples
cssresponsescale

Scale image within parent, retaining perspective, when larger then X


Trying to get a CSS only solution for the following problem.

I would like to display a variety of sized images within a container. If the image is larger then 80% viewport height, it should be scaled down to fit within the container.

Problem I am having is scaling to both a max-height and max-width (in order to accommodate both landscape and portrait images).

Here is a non-working JSFiddle as a starting point. None of the images should flow outside of the gray box. https://jsfiddle.net/0h5zkk0z/2/

<div id="container">
<img src="http://dummyimage.com/200x200/000/fff/?text=small" />
</div>
<div id="container">
<img src="http://dummyimage.com/400x700/000/fff/?text=portrait" />
</div>
<div id="container">
<img src="http://dummyimage.com/600x400/000/fff/?text=landscape" />
</div>

<style>
#container {
  max-height: 80vh;
  background-color: #ccc;
  position: relative;
  margin-bottom: 30px;
}
#container IMG {
  margin: 0 auto;
  display: block;
  width: auto;
  height: 100%;
}
</style>

Solution

  • .container {
      max-height: 80vh;
      background-color: #ccc;
      position: relative;
      margin-bottom: 30px;
    }
    
    .container img {
      margin: 0 auto;
      display: block;
      width: auto;
      max-height: inherit; //Inherits from container height
    }
    

    Btw: Please use an ID only once :-)

    Fiddle