Search code examples
htmlcssflexboxobject-fit

Make an image scales to maintain its aspect ratio while fitting within a flexbox


Considering the following code:

* {
  box-sizing: border-box;
  margin: 0;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: stretch;

  width: 400px;
  height: 200px;

  padding: 10px;

  background: red;
}
.box {
  flex: 1;
}
.box img {
  object-fit: contain;
}
<div class="container">
  <h1>lorem ipsum</h1>
  <figure class="box">
    <img src="http://lorempixel.com/400/200/">
  </figure>
</div>

I would expect object-fit: contain to make the img shrink into the .box, automatically sized by the flex container. Instead of my expectation, it overflows from the box. What is wrong in my code?


Solution

  • The .box should be display:flex too so that the img can "grow" within the .box.

    * {
      box-sizing: border-box;
      margin: 0;
    }
    
    .container {
      display: flex;
      flex-direction: column;
      width: 400px;
      height: 200px;
      padding: 10px;
      background: red;
    }
    .box {
      display: flex;
      flex: 1;
      overflow: hidden;
    }
    .box img {
      object-fit: contain;
    }
    <div class="container">
      <h1>lorem ipsum</h1>
      <figure class="box">
    <img src="http://placehold.it/400x200">
      </figure>
    </div>

    https://www.codeply.com/go/k0gsZbwwRq