Sub topic 4
Repeating tracks with repeat()
This chapter assumes you can write a grid container with display: grid, set grid-template-columns with fixed and fr values, and read basic CSS length units. Here you will learn how repeat() removes duplication from track lists and the mistakes that most often break it.
Why repeat() exists
Writing grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr; for a 12-column grid is noisy and easy to get wrong. The repeat() function is a shorthand that expands a track list a fixed number of times. It takes two arguments: a count and the track sizes to repeat.
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1rem;
}This is identical to 1fr 1fr 1fr 1fr. The browser expands it before it lays out the grid, so every other grid feature treats the result as four ordinary columns.
Repeating a pattern
The second argument can be a list of several tracks. The whole list is repeated as a unit.
.pattern {
display: grid;
grid-template-columns: repeat(2, 100px 1fr);
gap: 8px;
}This expands to 100px 1fr 100px 1fr. Use it when your design alternates track sizes, such as a label column followed by a value column.
Mixing repeat() with other tracks
You can place repeat() next to other track sizes in the same declaration. The .container example below has a fixed first column, then two equal columns made with repeat().
.container {
display: grid;
grid-template-columns: 200px repeat(2, 1fr);
grid-template-rows: repeat(2, auto);
gap: 16px;
}You can also use repeat() in grid-template-rows. A grid can contain more than one repeat() call in a single declaration, for example repeat(2, 1fr) 300px repeat(2, 1fr).
Common errors
- A count of zero or a negative number. The count must be a positive integer.
repeat(0, 1fr)is invalid, and the browser ignores the whole declaration. - A variable or fraction as the count.
repeat(2.5, 1fr)is invalid. Avar()is allowed only if it resolves to a valid integer. - Nesting repeat().
repeat(2, repeat(2, 1fr))is invalid. Write the pattern out once inside a singlerepeat(). - Forgetting the comma.
repeat(4 1fr)is a syntax error. The count and the track list are separated by a comma. - Expecting extra items to fit. If the grid has four columns and you add ten items, the extra items form new rows in the implicit grid. They do not create new columns.
Where this leads
The count in these examples is a fixed integer. A later chapter replaces it with the keywords auto-fill and auto-fit, which let the browser decide how many tracks fit. Those keywords build on the syntax you have just learned.
Exercise
Write a grid-template-columns declaration with repeat() that creates a 100px column, followed by three equal flexible columns, followed by another 100px column. How many column lines does the grid have?
Show answer
grid-template-columns: 100px repeat(3, 1fr) 100px; This creates five columns, so the grid has six column lines, numbered 1 to 6.