0

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?

rocambille
  • 15,398
  • 12
  • 50
  • 68

1 Answers1

1

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

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624