5

There is object-fit: contain as a way to resize the image so that the entire image fits within the frame, aligning the long side of the image with the frame.

h2 {
  font-family: Courier New, monospace;
  font-size: 1em;
  margin: 1em 0 0.3em;
}

div {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: flex-start;
  height: 940px;
}

img {
  width: 150px;
  height: 100px;
  border: 1px solid #000;
}

.narrow {
  width: 100px;
  height: 150px;
  margin-top: 10px;
}

.contain {
  object-fit: contain;
}
<div>

  <h2>object-fit: contain</h2>
  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="contain" />

  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="contain narrow" />

</div>

However, this does not work for div tags and so on, it works only for replacement elements.

 h2 {
  font-family: Courier New, monospace;
  font-size: 1em;
  margin: 1em 0 0.3em;
}

div {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: flex-start;
  height: 940px;
}

.contain-parent {
  width: 150px;
  height: 100px;
  background: red;
  border: 1px solid #000;
}

.narrow {
  width: 100px;
  height: 150px;
  background: green;
  margin-top: 10px;
}

.contain1 {
  width: 50px;
  height: 80px;
  background: blue;
  object-fit: contain;
}
.contain2 {
  width: 80px;
  height: 50px;
  background: blue;
  object-fit: contain;
}
<div>

  <h2>object-fit: contain(not work)</h2>
  <div class="contain-parent">
    <div class="contain1"></div>
  </div>

<div class="contain-parent">
    <div class="contain2 narrow"></div>
  </div>
</div>

How can I reproduce the same behavior as object-fit: contain on replacement elements with div tags, span tags and so on? I want to display letter box when the aspect ratio does not match.

  • 1
    You will have to do this manually using something like `vh` or `%` units; there is no property that allows for maintaining aspect ratios of non-replaced content in CSS. See if the `vh` solutions [here](https://stackoverflow.com/questions/39057453/maintain-aspect-ratio-of-flex-item), [here](https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css), and [here](https://stackoverflow.com/questions/34152213/flexbox-responsive-grid-of-square-divs-maintaining-aspect-ratio) solve your problems. – TylerH Feb 20 '19 at 17:01
  • As for the letter box effect, that will be even more additional styles. – TylerH Feb 20 '19 at 17:02

0 Answers0