Course contentsShow
← Web Development
Lesson 329 of 2,9826. CSS GridFree lesson

The repeat() Function for Grid Templates

Use repeat() notation to define repeating track patterns without redundant code.

The repeat() Function for Grid Templates

What you'll learn: How to use repeat() to create grid patterns without writing the same track sizes over and over.

When defining grid columns or rows, you'll often need multiple tracks with the same size. Instead of typing grid-template-columns: 1fr 1fr 1fr 1fr 1fr for five equal columns, CSS Grid provides the repeat() function as a shortcut.

How repeat() Works

The repeat() function takes two arguments: how many times to repeat, and what to repeat.

The syntax is:

repeat(count, track-size)

Here's a practical example:

.grid-container {
  display: grid;
  /* Instead of: grid-template-columns: 1fr 1fr 1fr 1fr; */
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

This creates four equal-width columns, each taking 1fr of available space.

Repeating Complex Patterns

You can repeat more than one track size at a time by listing multiple values:

.grid-container {
  display: grid;
  /* Repeats the pattern "200px 1fr" three times */
  grid-template-columns: repeat(3, 200px 1fr);
  /* Result: 200px 1fr 200px 1fr 200px 1fr */
}

This creates an alternating pattern of fixed and flexible columns.

Combining repeat() with Other Tracks

You can mix repeat() with regular track definitions:

.grid-container {
  display: grid;
  grid-template-columns: 100px repeat(3, 1fr) 100px;
  /* Result: 100px 1fr 1fr 1fr 100px */
}

Key Takeaway: The repeat() function eliminates repetitive code when defining grid templates, making your CSS cleaner and easier to maintain while creating consistent track patterns.