用CSS Grid实现积分商城礼品卡片网格,核心是display: grid配合auto-fit、minmax和响应式断点,兼顾移动端适配与视觉一致性。

在 H5 页面中用 CSS Grid 实现积分商城礼品卡片网格,核心是用 display: grid 控制列数、间距和响应式断点,兼顾移动端适配与视觉一致性。
基础网格结构:固定列数 + 自动换行
给卡片容器(如 .gift-grid)设置 Grid 布局,推荐用 grid-template-columns 配合 repeat() 和 auto-fit,让列数随容器宽度自动调整:
.gift-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 12px;
padding: 12px;
}说明:
• minmax(140px, 1fr) 表示每列最小 140px(保障卡片内容可读),最大均分剩余空间;
• auto-fit 会自动合并空余轨道,比 auto-fill 更适合卡片类布局;
• gap 统一控制卡片间距,避免用 margin 造成外边距塌陷问题。
卡片样式统一:固定宽高比 + 内容居中
礼品卡片建议采用等宽等高设计,提升视觉整齐度。可用 aspect-ratio(现代浏览器支持)或 padding-bottom 技巧兼容老版本:
- 现代写法(推荐):
.gift-card { aspect-ratio: 3 / 4; /* 宽高比 3:4 */ display: flex; flex-direction: column; align-items: center; justify-content: flex-start; border-radius: 8px; overflow: hidden; background: #fff; box-shadow: 0 2px 6px rgba(0,0,0,0.06); } - 兼容写法(需包裹内层):
.gift-card { position: relative; } .gift-card::before { content: ''; display: block; padding-bottom: 133%; /* 3:4 → 4/3 ≈ 133% */ } .gift-card > * { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
响应式断点:按屏幕宽度调整列数
对中大屏做微调,避免单行卡片过多导致信息过载:
- 手机(≤375px):1 列
- 小平板(376–767px):2 列
- 大平板及以上(≥768px):3 列(或 4 列,视设计而定)
.gift-grid {
grid-template-columns: repeat(1, 1fr);
}
@media (min-width: 376px) {
.gift-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 768px) {
.gift-grid {
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
}注意:断点数值需结合实际设计稿和测试设备调整,不建议死守标准值。
加载与空状态处理
真实项目中常需处理「无数据」或「加载中」状态,建议在 Grid 容器内直接插入占位元素:
- 加载中:用 3–4 个
.gift-card.skeleton卡片,配合背景动画(如linear-gradient+animation)模拟骨架屏; - 空状态:单独一个
.empty-state元素,设grid-column: 1 / -1跨满整行,居中显示图标和提示语。
这样既保持 Grid 结构稳定,又避免因动态渲染导致布局抖动。


















