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

如何用Flexbox与百分比响应式单位布局图片?解决两大布局问题

Flexbox响应式图片并排布局问题解决

问题1:justify-content失效的原因及修复

你给每个.service-item设了width:90%,三个子项宽度总和达270%,远超父容器100%的宽度上限。Flexbox默认flex-wrap: nowrap,子项会被强制挤在一行但总宽度溢出容器,此时容器没有剩余空间供justify-content分配,导致该属性完全失效。

修复方案:

  • 调整子项宽度,比如设为31%(搭配2%的子项间隙,三个子项加间隙刚好填满100%容器宽度);
  • 给父容器添加gap: 2%控制子项间距,再配合justify-content: space-between,即可实现均匀分布的并排布局。

问题2:图片宽高比例失调的修复

你给.service-item设置的height:65%没有明确的参照高度(父容器#services-container未定义高度),导致子项高度计算混乱;如果原图是竖版比例,height:auto会按原图比例渲染,自然出现高度大于宽度的情况。

修复方案:

  • 删除.service-item的height:65%,改用padding-top实现固定宽高比容器:比如要4:3比例就设padding-top:75%,1:1比例设padding-top:100%,数值为「高度/宽度×100%」;
  • 将图片设为绝对定位填充整个容器,再加object-fit: cover,让图片按比例缩放填充容器,不会拉伸变形,超出部分自动裁剪。

修改后的完整代码

CSS

.services h2 {
  margin: 3.125rem 0 2rem;
}

#services-container {
  display: flex;
  width: 100%;
  justify-content: space-between;
  gap: 2%;
}

.service-item {
  width: 31%;
  position: relative;
  padding-top: 75%; /* 4:3宽高比,可按需调整 */
  overflow: hidden;
}

.service-item img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

/* 可选:将标题固定在图片底部 */
.service-item h4 {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  margin: 0;
  padding: 1rem;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
}

HTML(无需修改)

<section class="services">
  <h2>our services</h2>
  <div id="services-container">
    <div class="service-item hotel">
      <img src="./resources/pictures/hotel.jpg" alt="hotel">
      <h4>The best hotels</h4>
    </div>
    <div class="service-item air-plane">
      <img src="./resources/pictures/airplane.jpg" alt="airplane">
      <h4>The best airline services</h4>
    </div>
    <div class="service-item food">
      <img src="./resources/pictures/food.jpg" alt="food">
      <h4>The highest quality foods</h4>
    </div>
  </div>
</section>

内容的提问来源于stack exchange,提问作者Hadi M Taheri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:20:22