全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-16 6 分钟 ✍️ juanwangdev

Grid布局之auto-fit/auto-fill

auto-fitauto-fill 配合 minmax() 创建自动响应的网格布局,根据容器宽度自动调整列数。

基本语法

CSS
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

auto-fill vs auto-fit

关键字行为特点
auto-fill尽可能多地填充轨道会保留空轨道
auto-fit自动调整轨道空轨道会塌陷,现有内容拉伸

auto-fill 行为

尽可能创建更多轨道,即使轨道为空。

CSS
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

假设容器宽度 1000px,每个轨道最小 200px:

  • 可放下 5 个轨道(200px × 5 = 1000px)
  • 如果只有 3 个子元素,会有 2 个空轨道

auto-fit 行为

创建轨道后,空轨道塌陷,现有内容拉伸填充。

CSS
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

假设容器宽度 1000px,每个轨道最小 200px,只有 3 个子元素:

  • 创建足够轨道后,空轨道塌陷
  • 3 个子元素会拉伸填充整个容器

可视化对比

CSS
/* auto-fill:保留空轨道 */
.fill {
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}

/* auto-fit:塌陷空轨道,内容拉伸 */
.fit {
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}
CSS
auto-fill(5个位置,3个内容):
[内容][内容][内容][ 空 ][ 空 ]

auto-fit(3个位置,内容拉伸):
[ 内容拉伸 ][ 内容拉伸 ][ 内容拉伸 ]

实际应用

响应式卡片网格

HTML
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
}
CSS
<div class="card-grid">
  <div class="card">卡片 1</div>
  <div class="card">卡片 2</div>
  <div class="card">卡片 3</div>
</div>

固定宽度项目

CSS
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, 250px);
  /* 每个项目固定 250px,自动换行 */
  gap: 20px;
  justify-content: center;
}

图片画廊

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 10px;
}

.gallery img {
  width: 100%;
  aspect-ratio: 1;
  object-fit: cover;
}

选择建议

场景推荐原因
内容需要拉伸填满auto-fit空轨道塌陷,内容自动拉伸
保持项目尺寸auto-fill保留空位,项目不拉伸
居中排列少量内容auto-fill + justify-content: center居中效果更好
text
/* 少量内容居中 */
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  justify-content: center;
  gap: 20px;
}

要点总结

  • auto-fill:尽可能多创建轨道,保留空轨道
  • auto-fit:创建轨道后塌陷空轨道,内容拉伸
  • 配合 minmax() 实现响应式:repeat(auto-fit, minmax(200px, 1fr))
  • 无需媒体查询即可实现自动适应布局

📝 发现内容有误?点击此处直接编辑

← 上一篇 Grid-template-areas 命名区域布局
下一篇 → Grid布局之fr单位参数深入理解
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库