如何在保留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
相关产品推荐
相关产品推荐

