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

如何在div宽度小于图片宽度时保持图片居中显示

解决方案

问题核心是你给图片设置了justify-content: center,但这个属性是flex容器专属样式,不能直接用在图片元素上;同时你的图片容器imgbox未开启flex布局,导致居中规则完全不生效,最终容器宽度小于图片宽度时,图片无法保持居中对齐。

修改以下CSS代码即可解决问题:

.deel1 {
  display: block; /* 替换原inline-block,避免不必要的间距问题 */
  height: 100vh;
  width: 100%;
}

.deel1 .imgbox {
  height: 100vh;
  width: 100%;
  background-color: rgba(200, 200, 200, 1.0);
  /* 开启flex布局,让子元素水平+垂直居中 */
  display: flex;
  justify-content: center;
  align-items: center;
  /* 容器变窄时,裁剪图片溢出部分 */
  overflow: hidden;
}

.deel1 .imgbox .img {
  height: 100%;
  /* 保持图片比例,完整适配容器高度 */
  object-fit: contain;
}

关键修改说明:

  • display: flex + justify-content: center + align-items: center:让图片在容器内始终保持水平、垂直双方向居中,不受容器尺寸变化影响。
  • overflow: hidden:当图片宽度超过容器时,自动裁剪溢出区域,同时保留图片居中状态。
  • object-fit: contain:确保图片比例不变,完整显示在容器内(若需要图片铺满容器且保持比例,可替换为object-fit: cover)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:30:59