Search code examples
javascriptcssimageaspect-ratio

Set image max-width and max-heigth 100% but allow the image to scale larger than 100% of itself


I'm trying to scale an image to 100% of it's parent. The aspect ratio of the image should stay the same, so the 100% scale should be either 100% of the width or 100% of the height, whichever comes first. I've tried using

max-height: 100%;
max-width: 100%;

This works as long as the image is larger than it's container. As soon as the container becomes larger than the image, the image no longer stretches to an edge but stays at 100% of it's size.

Browser support is an issue, Ive tried flexbox with object-fit: contain; but I have to support IE10.

Consider the following:

.img-container {
  border: solid red 1px;
  margin-bottom: 10px;
}
.img-container img {
  max-height: 100%;
  max-width: 100%;
  border: solid green 1px;
}
.size1 {
  width: 200px;
  height: 50px;
}
.size2 {
  height: 200px;
  width: 50px;
}
.size3 {
  width: 650px;
  height: 650px;
}
<div class="img-container size1">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

<div class="img-container size2">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

<div class="img-container size3">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

The images inside .size1 and .size2 scale correctly, but the container for .size3 is larger than the image, this one should stretch to the edge as well.

How do I go about doing this? Pure CSS is preferred, but JS is not out of the question.


Solution

  • Have a look at this solution using jQuery.

    $(document).ready(function(){
     $('img').each(function(){
      let imgHeight = $(this).height();
      let containerHeight = $(this).closest('.img-container').height();
      if(imgHeight > containerHeight){
        $(this).css('width','auto');
        $(this).css('height', '100%');
      }
     });
    });
    .img-container {
      border: solid red 1px;
      margin-bottom: 10px;
    }
    .img-container img {
      width: 100%;
      height: auto;
      border: solid green 1px;
    }
    .size1 {
      width: 200px;
      height: 50px;
    }
    .size2 {
      height: 200px;
      width: 50px;
    }
    .size3 {
      width: 650px;
      height: 650px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="img-container size1">
     <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
    </div>
    
    <div class="img-container size2">
     <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
    </div>
    
    <div class="img-container size3">
     <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
    </div>