如何用 Grid 实现响应式卡片布局(自动调整列数)?
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 20px;
}
原理
auto-fill:自动填充尽可能多的列
minmax(280px, 1fr):每列最小 280px,最大等分剩余空间
- 当容器宽度 < 280px 时,自动变为单列
- 当容器宽度增加时,自动增加列数
效果
宽屏(1200px):4列
┌──┐ ┌──┐ ┌──┐ ┌──┐
│ │ │ │ │ │ │ │
└──┘ └──┘ └──┘ └──┘
中屏(800px):3列
┌──┐ ┌──┐ ┌──┐
│ │ │ │ │ │
└──┘ └──┘ └──┘
窄屏(500px):1列
┌──┐
│ │
└──┘
auto-fill vs auto-fit
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
完整响应式示例
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr));
gap: 20px;
padding: 20px;
}
适合场景
同分类其他题目