CSS Reference ยท Functions
The repeat() function
Reference for the CSS repeat() function: repeating grid track lists a fixed number of times, or with auto-fill and auto-fit, plus syntax and live examples.
The repeat() function writes a list of grid tracks once and repeats it. Instead of 1fr 1fr 1fr 1fr, you write repeat(4, 1fr). It is only valid inside the track-list properties of a grid container, such as grid-template-columns and grid-template-rows.
Besides a fixed count, repeat() accepts the keywords auto-fill and auto-fit. They let the browser decide how many tracks fit in the container, which is the foundation of grids that adapt to any width without media queries.
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; }
Try it
Resize the preview and the last grid changes its column count while the first two stay fixed.
Syntax
repeat( <count>, <track-list> ) /* <count> is one of: */ /* a positive integer repeat(3, 1fr) */ /* auto-fill as many tracks as fit */ /* auto-fit as auto-fill, then collapse */ /* empty tracks */
- Where it works: in
grid-template-columns,grid-template-rowsand thegrid-templateshorthand. - Inherited: not applicable (it is a function, not a property).
- Animatable: not as such; the track list as a whole can interpolate only when both sides have the same structure.
Values
| Argument | Description |
|---|---|
| Integer (1 or more) | Repeat the track list exactly this many times. |
auto-fill |
Create as many repetitions as fit in the container. Empty repetitions still take space. |
auto-fit |
Same count as auto-fill, but tracks that hold no items collapse to zero width, so the remaining tracks can grow. |
| Track list | One or more track sizes (1fr, 100px, minmax(), ...), optionally with line names in square brackets. |
Usage notes
- No nesting.
repeat()cannot contain anotherrepeat(). Write severalrepeat()calls side by side instead. - Automatic repetition needs a definite size. With
auto-fillorauto-fitevery track must have a fixed maximum or minimum size, which is whyminmax(120px, 1fr)works butrepeat(auto-fill, 1fr)is invalid. Only one automaticrepeat()is allowed per track list. - Fixed tracks can surround it.
200px repeat(auto-fill, 100px) 200pxis valid. auto-fillvsauto-fit. They differ only when there are fewer items than possible tracks:auto-fillleaves empty columns in place,auto-fitcollapses them so items stretch.- Line names repeat too.
repeat(2, [col] 1fr)creates two lines both namedcol. - Prefer
minmax(min(100%, 200px), 1fr)if the minimum might be wider than a small container; otherwise the grid can overflow.
Browser support
Supported in all current browsers; repeat() has been part of CSS Grid since grids first shipped.
Related
grid-template-columnsโ whererepeat()is used mostgrid-template-rowsminmax()โ the usual partner forauto-fill- Lessons: Grid tracks, Grid patterns