3

object-fit: contain一种方法可以调整图像的大小,使整个图像适合框架,将图像的长边与框架对齐。

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>

但是,这不适用于 div 标签等,它仅适用于替换元素。

 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>

如何object-fit: contain使用 div 标签、span 标签等重现与替换元素相同的行为?当纵横比不匹配时,我想显示信箱。

4

0 回答 0