Home > database >  Display image original size, if possible, else shrink
Display image original size, if possible, else shrink

Time:11-07

There are lots of questions on this general subject, but none that do what I need.

I need to present multiple images, each in a div of its own, but I have no prior knowledge of whether they're portrait, landscape, or low resolution. What I want to do is show them original size (and centered) if they will fit (i.e. I don't want to stretch a low-resolution image), but if they're larger than the div then shrink them appropriately according to their aspect ratio.

This sounds simple but I gave up with the img element, and solutions suggesting width:100%;height:auto; were neglecting the fact that this presumes a landscape image.

I started using background properties and had much more success. If I could make this work then it would have the added benefit that it worked with IE11 too. For instance:

background-image: url("http://example.jpg");
background-position:center center;
background-size: auto;
background-repeat: no-repeat;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

works fine if the image is smaller than the div, but crops the image if the original size is too large.

Is there a way to scale the size appropriately in this case (as with background-size:contain), but display original size when possible?

CodePudding user response:

I think you can achieve what you want with a combination of the two properties: max-width: 100% and max-height: 100%:

.container {
  display: flex;
}

.item {
  margin: 1rem;
  width: 200px;
  height: 200px;
  
  border: 1px solid;
  
  display: flex;
}

img {
  max-width: 100%;
  max-height: 100%;
  
  margin: auto;
}
<div class="container">
  <div class="item">
    <img src="https://via.placeholder.com/150x150" />
  </div>
  <div class="item">
    <img src="https://via.placeholder.com/300x200" />
  </div>
  <div class="item">
    <img src="https://via.placeholder.com/200x300" />
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

1st item: image is smaller, keeps its original size.
2nd item: image is landscape, shrinked to fit.
3rd item: image is portrait, shrinked to fit.

Is this what you needed?

  • Related