repeat()函数可简洁定义多列布局,如repeat(4, 1fr)替代冗长的1fr 1fr 1fr 1fr;支持与固定尺寸组合如200px repeat(3, 1fr) 80px;配合auto-fit/auto-fill实现响应式列数调整;仅接受正整数、auto-fit或auto-fill,不支持嵌套或小数。

用 repeat() 函数写多列布局,比手动写一堆 1fr 简洁得多,也更易维护。
用 repeat() 替代重复的 track 定义
以前写 4 列等宽布局要这样写:
grid-template-columns: 1fr 1fr 1fr 1fr;现在只需一行:
grid-template-columns: repeat(4, 1fr);想改成 6 列?改个数字就行,不用增删字段。
立即学习“前端免费学习笔记(深入)”;
组合使用 repeat() 和固定尺寸
实际布局常混用固定列和弹性列,比如侧边栏 + 主内容区:
grid-template-columns: 200px repeat(3, 1fr) 80px;这表示:200px 宽的左栏 → 3 个等宽主列 → 80px 宽的右栏。repeat() 可嵌在任意位置,不局限于开头或结尾。
用 auto-fit / auto-fill 动态适配列数
响应式场景下,让列数随容器宽度自动调整:
- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) );
- grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)) );
区别在于:auto-fit 会收缩空列(把剩余空间分给现有列),auto-fill 保留所有可能列(空列仍占位)。多数情况推荐 auto-fit。
避免常见误区
-
repeat() 只接受正整数、auto-fit 或 auto-fill,不能写
repeat(-2, 1fr)或repeat(1.5, 1fr) - 嵌套 repeat 不被支持,比如
repeat(2, repeat(3, 1fr))是无效语法 - 和
minmax()搭配时,注意括号层级:正确是repeat(3, minmax(100px, 1fr)),不是minmax(repeat(3, 100px), 1fr)










