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

如何用CSS Grid实现可变高度的瀑布流(Masonry)布局

使用CSS实现瀑布流(Masonry)布局的解决方案

我尝试用CSS Grid创建瀑布流布局,网格内项高度可变,希望下一行的项能填充上一行的空隙。使用flex-flow: row wrap未达到预期效果,以下是预期效果、原有代码:

预期效果

瀑布流预期效果

原有HTML代码

<div class="container">
  <div class="g grid-33">Item 1</div>
  <div class="g grid-66">Item 2</div>
  <div class="g grid-33">Item 3</div>
  <div class="g grid-33">Item 4</div>
  <div class="g grid-33">Item 5</div>
  <div class="g grid-66">Item 6</div>
  <div class="g grid-33">Item 7</div>
</div>

原有CSS代码(Flex实现)

.container {
  display: flex;
  flex-wrap: wrap;
  padding: 15px 15px 0 0;
  background: #CDD6D0;
}

.g {
    background: #E16036;
    border: 4px solid #E3170A;
    border-radius: 8px;
    padding: 15px;
    color: white;
    font: 18px Arial;
    margin: 0 0 15px 15px;
    height: fit-content;
}

.grid-25 {
  width: calc(25% - 15px);
}

.grid-33 {
  width: calc(33.3333% - 15px);
}

.grid-50 {
  width: calc(50% - 15px);
}

.grid-66 {
  width: calc(66.6666% - 15px);
}

.grid-100 {
  width: calc(100% - 15px);
}

.g:nth-child(2) {
    height: 100px;
}

.g:nth-child(3) {
    height: 90px;
}

.g:nth-child(6) {
    height: 100px;
}

.g:nth-child(5) {
    height: 90px;
}

解决方案:改用CSS Grid实现

Flex布局基于行级排列,无法自动填充垂直空隙,而CSS Grid通过以下配置可实现需求:

修改后的CSS代码:

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3等分列布局 */
  grid-auto-flow: dense; /* 自动填充布局空隙 */
  gap: 15px; /* 统一设置项间距,替代margin计算 */
  padding: 15px;
  background: #CDD6D0;
}

.g {
  background: #E16036;
  border: 4px solid #E3170A;
  border-radius: 8px;
  padding: 15px;
  color: white;
  font: 18px Arial;
}

/* 用Grid列跨度替代宽度类 */
.grid-33 {
  grid-column: span 1; /* 占据1列 */
}

.grid-66 {
  grid-column: span 2; /* 占据2列 */
}

.g:nth-child(2) {
  height: 100px;
}

.g:nth-child(3) {
  height: 90px;
}

.g:nth-child(6) {
  height: 100px;
}

.g:nth-child(5) {
  height: 90px;
}

关键说明

  • grid-template-columns: repeat(3, 1fr):创建3个等宽列,比百分比宽度更灵活易维护
  • grid-auto-flow: dense:核心属性,让Grid自动寻找并填充布局中的空隙,实现瀑布流的填充效果
  • gap:替代原有margin实现项间距,避免复杂的calc计算
  • grid-column: span N:直接指定项占据的列数,更符合Grid布局的逻辑

修改后即可实现预期的瀑布流效果,下一行的项会自动填充上一行的可用空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:43:15