【问题标题】:What's the best way to enlarge the height of image to max-height?将图像高度放大到最大高度的最佳方法是什么?
【发布时间】:2018-07-06 14:34:18
【问题描述】:

我有一个显示图像的容器,该容器具有固定的 100% 宽度。我的要求是:

  • 图片不改变纵横比
  • 如果图片更宽,宽度为100%,高度应小于max-height
  • 如果图片更高,高度应该是max-height,宽度小于100%。

在我的示例中,前两个图像显示正确。但是,第三张图片是错误的,因为宽度没有达到 100% 或者高度没有达到最大高度。

我该如何解决这个问题?

.container {
  border: 1px solid black;
  height: 200px;
  width: 100%;
}

img {
  max-width: 100%;
  max-height: 200px;
  width: auto;
  display: block;
  margin: auto;
}
<div class="container">
  <img src="https://i.stack.imgur.com/kZPXw.png" />
</div>

<div class="container">
  <img src="https://i.stack.imgur.com/IfTIL.png" />
</div>

<div class="container">
  <img src="https://www.gravatar.com/avatar/62345e20906dbccbf7e18f11ab4bd047?s=64&d=identicon&r=PG&f=1" />
</div>

你也可以在这里玩:https://jsfiddle.net/d425c1bh/2/

【问题讨论】:

  • 所以...澄清一下...任何必须扩展(或收缩)(保持纵横比),直到它达到或达到 100% 或宽度或最大高度。对吗?
  • @Dknacht,抱歉,我发现代码无法重现我的真实问题,让我更新。
  • @Dknacht,确认没有问题。是的,你是对的,要么达到 100% 宽度,要么达到 100% 最大高度
  • 请检查答案。
  • img 标签是空标签,所以不要使用&lt;img&gt;&lt;/img&gt;,而是使用&lt;img /&gt;。检查w3schools.com/tags/tag_img.asp

标签: html css


【解决方案1】:

试试这个,添加 object-fit 并将宽度 auto 替换为宽度 100%

.container {
  border: 1px solid black;
  height: 200px;
  width: 100%;
}

img {
  max-height: 200px;
  width: 100%;
  max-width: 100%;
  object-fit: contain;
  display: block;
  margin: auto;
}

看到它在工作here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多