css Grid实现商品列表多列排版需设容器display: grid,用grid-template-columns控制列数与宽度、gap控制间距;支持固定列宽(如minmax(280px,1fr))和响应式断点切换(手机1列、平板2列、桌面3-4列),配合flex布局实现等高卡片与内容对齐,并注意兼容性处理及父容器宽度约束。

用 CSS Grid 实现商品列表的多列排版,核心是把容器设为 display: grid,再通过 grid-template-columns 控制列数和宽度,配合 gap 控制间距,简洁又响应灵活。
基础多列布局(固定列宽)
适合屏幕宽度较稳定、商品卡片尺寸统一的场景。例如每列 280px,自动换行:
.product-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; }
说明:
– repeat(auto-fill, ...) 让浏览器尽可能多地填满可用空间;
– minmax(280px, 1fr) 表示每列最小 280px,剩余空间平均分配;
– gap 同时控制行距和列距,比 margin 更干净。
响应式列数控制(按断点切换)
不同屏幕下显示不同列数,更符合实际浏览习惯:
- 手机(≤480px):1 列
- 平板(481px–768px):2 列
- 桌面(≥769px):3 或 4 列
对应 CSS:
立即学习“前端免费学习笔记(深入)”;
.product-list { display: grid; grid-template-columns: 1fr; gap: 16px; } @media (min-width: 481px) { .product-list { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 769px) { .product-list { grid-template-columns: repeat(3, 1fr); } }
@media (min-width: 1024px) { .product-list { grid-template-columns: repeat(4, 1fr); } }
等高商品卡片 + 内容对齐
Grid 天然支持行内元素等高,但需注意子项内容对齐方式:
- 给商品项(如
.product-item)加display: flex; flex-direction: column;,让内部标题、价格、按钮垂直排列 - 用
justify-content: space-between;推开底部按钮,保持卡片底部对齐 - 图片建议统一宽高比(如
aspect-ratio: 4/3;),或用Object-fit: cover;防止拉伸变形
兼容性与兜底处理
Grid 在现代浏览器中支持良好(chrome 57+/firefox 52+/safari 10.1+),若需兼容 IE,可加简单 fallback:
.product-list { display: -ms-grid; /* IE10-11 */ display: grid; -ms-grid-columns: 1fr 1fr; /* IE 需手动写列数 */ grid-template-columns: repeat(2, 1fr); }
更稳妥的做法是用 @supports 进行特性检测,只对支持 Grid 的浏览器启用:
@supports (display: grid) { .product-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 20px; } }
不复杂但容易忽略:确保父容器有足够宽度,且商品项没有意外的 Float、inline 或固定 width 干扰 Grid 自动计算。