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

如何使用CSS Grid无明确高度堆叠同宽异高元素并消除空隙

纯CSS Grid实现无固定高度的有序堆叠布局

Great question! This kind of layout—where you have elements of equal width but variable, content-driven heights, stacked in a specific order with no gaps—is exactly what CSS Grid was built for, and you don’t need to hardcode heights or manually map out grid areas to pull it off.

Let’s break down a better approach than the template areas method in your example:

Solution Code

<div class="container">
  <div class="box box1">1<br>(Height determined by content)</div>
  <div class="box box2">2<br>Short content</div>
  <div class="box box3">3<br>Medium<br>content</div>
  <div class="box box4">4<br>Medium<br>content</div>
  <div class="box box5">5<br>Long content<br>Long content<br>Long content<br>Long content</div>
  <div class="box box6">6<br>Medium-long<br>content<br>content</div>
</div>
.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr; /* 2 equal-width columns */
  gap: 0; /* Remove gaps between boxes */
  align-items: start; /* Align boxes to the top of their grid cells */
}

.box {
  border: solid 1px;
}

/* Control stacking order with row spanning */
.box1 {
  background-color: yellow;
  grid-row: span 4; /* Span 4 rows to match the total height of box2-box4 */
}

.box6 {
  background-color: gray;
  grid-row: span 2; /* Span 2 rows to align with box5's height */
}

How It Works

  • No fixed heights: All box heights are determined by their content—no need to set height values manually.
  • grid-template-columns: 1fr 1fr: Creates two equal-width columns without locking in pixel widths (Grid handles the spacing automatically).
  • gap: 0: Ensures there are no unwanted gaps between elements (adjust this to 5px or similar if you want small spacing).
  • grid-row: span N: This is the magic. By telling elements how many rows to span, you control their vertical placement relative to other elements. Grid automatically adjusts row heights to fit content, so your boxes stack perfectly without gaps.

If you need even more flexibility (and don’t mind letting Grid fill gaps where possible), you could add grid-auto-flow: dense to the container. Just note that dense will reorder elements to fill empty space, which might break your desired stacking order—stick with the grid-row: span method if you need strict control over the sequence.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:32:41