You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在保留img-box容器时维持图片宽高比(排除两种方案)

问题:图片(img)高度大于img-box容器

问题示意图

我找到了两种解决方法,但不想采用:

  • 移除img-box包裹容器
  • 在img标签中使用max-height: 100vh; max-width: 100vw;样式

当前代码

CSS

body {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}

.wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 300px;
  height: 500px;
  background: red;
  overflow: hidden;
}

.img-box {
  width: auto;
  height: auto;
}

img {
  max-width: 100%;
  max-height: 100%;
  height: auto;
  width: auto;
}

HTML

<div class="wrap">
  <div class="img-box">
    <img src="https://picsum.photos/900/500" alt="" />
  </div>
</div>
<div class="wrap">
  <div class="img-box">
    <img src="https://picsum.photos/200/600" alt="" />
  </div>
</div>

可行解决方案

给img-box添加样式,让它受父容器wrap的尺寸约束,同时确保图片正确缩放:

.img-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

这样修改后,img-box会填满wrap的空间,图片的max-width和max-height会基于img-box的尺寸生效,既能保持原图比例,又不会超出红色容器范围。

如果不想让img-box强制填满容器,也可以用这个方案:

.img-box {
  max-height: 100%;
  max-width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

这种方式下img-box只会占据图片所需的最大空间,但不会超出wrap的尺寸限制,图片同样能正常适配。

内容的提问来源于stack exchange,提问作者flyflydogdog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:05:27