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

Flex items高度不同致留白,如何实现紧凑拼图式布局?

解决Flex布局下紧凑拼图的空白问题

你的布局在屏幕宽度≥768px时出现空白,核心原因是Flex默认的行布局特性:每行高度由该行内最高元素决定。section1高度100px,section2高度200px,导致第一行被拉伸至200px,section1下方自然留出100px空白,section3只能从第二行开始排列。

推荐方案:使用CSS Grid布局

Grid天生适配这种不规则拼图布局,能精准控制元素位置和跨度,实现紧凑排列:

修改后的完整代码:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
    }

    .container {
      display: grid;
      grid-template-columns: 1fr 1fr; /* 桌面端两列等宽 */
    }

    .section {
      box-sizing: border-box;
      padding: 20px;
    }

    .section-1 {
      background-color: #f1c40f;
      height: 100px;
    }

    .section-2 {
      background-color: #2ecc71;
      height: 200px;
      grid-row: span 2; /* 让section2占据2行高度,对齐section1+section3的上半部分 */
    }

    .section-3 {
      background-color: #3498db;
      height: 300px;
      grid-row: 2 / -1; /* 让section3从第2行开始,紧跟section1下方 */
    }

    /* 移动端恢复单列布局 */
    @media (max-width: 767px) {
      .container {
        grid-template-columns: 1fr;
      }
      .section-2, .section-3 {
        grid-row: auto;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="section section-1">
      Section 1 - Height: 100px
    </div>
    <div class="section section-2">
      Section 2 - Height: 200px
    </div>
    <div class="section section-3">
      Section 3 - Height: 300px
    </div>
  </div>
</body>
</html>

原理说明

  • grid-template-columns: 1fr 1fr 定义桌面端两列等宽布局
  • grid-row: span 2 让section2占据两行,刚好匹配section1(100px)+ section3的上100px高度
  • grid-row: 2 / -1 让section3从第二行开始,直接衔接section1底部,填满左侧剩余空间

备选方案(不推荐):Flex负margin调整

如果坚持用Flex,可通过负margin偏移实现,但仅适用于固定高度场景,灵活性差:

@media (min-width: 768px) {
  .section {
    width: 50%;
  }
  .section-3 {
    margin-top: -100px; /* 向上偏移填补空白 */
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:02:08