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

如何阻止Grid网格项拉伸?实现固定间距3*3网格

实现不拉伸的3*3规整Grid布局

你当前的问题出在grid-template-columns: repeat(3, 1fr)——1fr会让每列均分网格容器的可用宽度,导致网格列本身被拉伸(虽然你的item设置了固定宽,但列的宽度会撑大,视觉上看起来像是item周围有多余空间)。要让网格项不拉伸且保持40px的横竖间距,有两种简单方案:

方案1:直接指定列宽为item的固定宽度

把列宽设置为和item一致的40px,这样每列宽度固定,不会随页面拉伸:

.outGrid {
  display: grid;
  grid-gap: 40px;
  grid-template-columns: repeat(3, 40px);
  /* 可选:让网格容器在页面水平居中 */
  margin: 0 auto;
}

.item {
  width: 40px;
  height: 40px;
  background-color: grey;
}

此时网格容器总宽度为3*40px + 2*40px = 200px(3个item宽度 + 2个横向间距),完全固定,不会随页面宽度变化。

方案2:使用min-content适配内容宽度

如果后续item宽度可能变化,用min-content让列宽自动适配内容的最小宽度,效果和方案1一致,但更灵活:

.outGrid {
  display: grid;
  grid-gap: 40px;
  grid-template-columns: repeat(3, min-content);
  /* 可选:让网格容器在页面水平居中 */
  margin: 0 auto;
}

.item {
  width: 40px;
  height: 40px;
  background-color: grey;
}

两种方案都能保证item不被拉伸,同时横竖间距保持40px,形成规整的3*3网格。

内容的提问来源于stack exchange,提问作者one-hand-octopus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:50:39