Search code examples
htmlcssflexboxobject-fit

Remove whitespace from left and right of resized image


I have a fixed height container in which I'd like to display an image and a caption. The requirement is that the image should scale to fit the available height while maintaining aspect ratio. The caption could be of variable height.

Below is a JS fiddle of what I have so far. I am unable to get the whitespace on the right and left side of the images to disappear (I've added a border to the img tag to show what I mean). Is it possible to remove the excess whitespace?

https://jsfiddle.net/peL1a7vj/1/

HTML

<div class="container">
  <div class="item">
    <img class="image" src="https://www.stockvault.net/data/2009/07/14/109489/thumb16.jpg"/>
    <div class="text">
      Caption 1
    </div>
  </div>
  <div class="item">
    <img class="image" src="https://images.unsplash.com/photo-1591870509558-26b7eee6d549"/>
    <div class="text">
      Caption 2
    </div>
  </div>
</div>

CSS

.container {
  height: 200px;
  flex: 1 1 auto;
  display: flex;
  flex-flow: row nowrap;
  overflow-x: auto;
  overflow-y: hidden;
}
.item {
  display: flex;
  flex-direction: column;
}
.text {
  flex: 0 0 auto;
}
.image {
  flex: 1 1 auto;
  overflow: hidden;
  object-fit: contain;
  max-height: 100%;
  width: auto;
  border: solid;
}

This is similar to CSS object-fit: contain; is keeping original image width in layout but I was unable to fix it using the methods suggested in the accepted answer


Solution

  • "The requirement is that the image should scale to fit the available height while maintaining aspect ratio" - that's what it does in your code! If you would stretch the width ("to fill the whitespace"), either you would loose the aspect ratio and get a distorteded image, or - if the ratio is kept - the top and bottom of the image would be cut off since it would grow due to the extended width.

    There is no other solution: Either there is some whitespace, or some of the image is cut off, or the image is distorted. Unless you change the dimensions of the parent container:

    The only situation where your wish could be fulfilled: When the parent of the image has the same height/width proportion as the original image. So you would have to set height and width for the container accoring to the proportions of the image.