cssflexboxobject-fit

Mysterious behavior when using CSS "object-fit:contain" property on images inside a flexbox container having a specific height


I've got a flexbox container in which I'm trying to display two images with drop-shadows side-by-side. I want them to take equal amounts of horizontal space even though the images differ in size. I'm using a container with style "display: flex" and using "object-fit: contain" for the images to cause them to scale. My code works if I don't give the container a specific height. If I give the container a specific height, such as 300px, the images scale down, but the drop-shadow appears at a distance from the image edges as though there's a box wrapping them. This seems odd behavior. Can anyone explain this odd-seeming behavior, and is there a way in which I can give the container a height and still get it to work?

Fiddle to illustrate: https://jsfiddle.net/Lej1a6vp/

html:

 <div class="container">
    <img class="image" src="http://via.placeholder.com/300x400" />   
    <img class="image" src="http://via.placeholder.com/400x300" />
  </div>

css:

.container {
  display: flex;
  margin: 1em auto 3em auto;
  width: 500px;
  height: 200px;
  justify-content: center;
  align-items: center;
}
img {
  box-shadow: 8px -8px 10px #00000080;
  height: 100%;
  width: 40%;
  margin-left: 1em;
  object-fit: contain;
}

Solution

  • BDB88 provided me with the clue I needed, and thanks for that. My objective is to make a responsive layout that will show the drop shadow around the images and not some ghostly outline that's at a distance, and I want to keep the images' aspect ratios. I also want to mandate a particular height for the container, and not have the images overflow outside of it. My use of "height: 100%;" for the img tag was what was causing the problem. Combining that with the "width: 40%;" was causing conflict because both requirements can't always be satisfied simultaneously. By changing to "max-height: 100%;" and "max-width: 40%;" for the img tag, I'm getting the behavior that I was after. The CSS is now (I made some additional edits to make the behavior more apparent when viewing and scaling the window to simulate larger/smaller screen sizes):

    .container {
      background: yellow;
      display: flex;
      margin: 1em auto 3em auto;
      width: auto;
      height: 200px;
      justify-content: center;
      align-items: center;
    }
    img {
      box-shadow: 8px -8px 10px #00000080;
      max-width: 40%;
      max-height: 100%;
      margin-left: 1em;
      object-fit: contain;
    }