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

如何用CSS创建按列流动的3列Grid布局?

解决方案:纯CSS实现列优先的3列网格布局

你的问题在于使用grid-auto-flow: column时,固定3列的Grid会自动新增列来容纳所有元素,导致元素排成一行。以下是两种纯CSS解决方案,实现你需要的列优先填充、行数自动生成的效果:

方案1:CSS多列布局(推荐,最简单)

多列布局天然支持列优先排列,固定列数后元素会从上到下填满第一列,再依次填充后续列,完全匹配你的需求:

.parent-div {
  /* 设置3列 */
  columns: 3;
  /* 可选:设置列之间的间距 */
  column-gap: 1em;
}

/* 可选:避免子元素被拆分到不同列中 */
.parent-div > * {
  break-inside: avoid;
  /* 可选:增加元素之间的垂直间距 */
  margin-bottom: 1em;
}

效果示例

11个元素的排列结果如下:

[1] [5] [9]
[2] [6] [10]
[3] [7] [11]
[4] [8]

方案2:CSS Grid精确控制(适合需要Grid特性的场景)

如果必须使用Grid,可以通过nth-child选择器和CSS变量指定每个元素的网格位置:

.parent-div {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: auto;
  /* 可选:网格间距 */
  gap: 1em;
}

/* 第一列元素:第1、4、7、10...个 */
.parent-div > :nth-child(3n + 1) {
  grid-column: 1;
  grid-row: calc((var(--index) - 1) / 3 + 1);
}

/* 第二列元素:第2、5、8、11...个 */
.parent-div > :nth-child(3n + 2) {
  grid-column: 2;
  grid-row: calc((var(--index) - 2) / 3 + 1);
}

/* 第三列元素:第3、6、9...个 */
.parent-div > :nth-child(3n + 3) {
  grid-column: 3;
  grid-row: calc((var(--index) - 3) / 3 + 1);
}

需要给每个子元素添加--index变量(若元素数量不固定,建议配合少量JS自动设置,否则需手动添加):

<div class="parent-div">
  <div style="--index: 1">[1]</div>
  <div style="--index: 2">[2]</div>
  <div style="--index: 3">[3]</div>
  <!-- 更多元素 -->
</div>

适用场景

  • 方案1:适合大多数场景,无需额外配置,代码简洁。
  • 方案2:当需要利用Grid的对齐、行高控制等高级特性时使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:01:10