Grid布局之auto-fit/auto-fill
auto-fit 和 auto-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)) - 无需媒体查询即可实现自动适应布局
📝 发现内容有误?点击此处直接编辑