How to Use repeat() in CSS Grid for Easy Layouts
Use the
repeat() function in CSS Grid to define repeated columns or rows easily by specifying the number of repetitions and the size. For example, grid-template-columns: repeat(3, 1fr); creates three equal columns. This helps keep your CSS concise and clear when you want multiple tracks of the same size.Syntax
The repeat() function takes two parts: the number of times to repeat, and the size of each repeated track.
- repeat(count, size):
countis how many times to repeat. sizeis the width for columns or height for rows, like100px,1fr, orauto.
css
grid-template-columns: repeat(4, 100px); grid-template-rows: repeat(2, 50px);
Example
This example creates a grid with 3 equal columns and 2 equal rows using repeat(). Each cell has a border so you can see the layout clearly.
css
html, body {
height: 100%;
margin: 0;
font-family: Arial, sans-serif;
}
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 100px);
gap: 10px;
width: 60vw;
max-width: 600px;
border: 2px solid #333;
padding: 10px;
}
.cell {
background-color: #a0c4ff;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 1.2rem;
color: #023e8a;
}Output
<div class="container">
<div class="cell">1</div>
<div class="cell">2</div>
<div class="cell">3</div>
<div class="cell">4</div>
<div class="cell">5</div>
<div class="cell">6</div>
</div>
Common Pitfalls
One common mistake is forgetting that the count in repeat() must be a positive integer or auto-fill/auto-fit. Also, mixing units inside repeat() can cause unexpected layouts.
Another pitfall is using repeat() inside shorthand properties incorrectly, like grid-template, which requires careful syntax.
css
/* Wrong: count is not a number */ grid-template-columns: repeat(auto, 100px); /* invalid */ /* Correct: use auto-fill or auto-fit for dynamic repeats */ grid-template-columns: repeat(auto-fill, 100px);
Quick Reference
repeat() helps you write cleaner CSS for grids by repeating track sizes.
repeat(3, 1fr): 3 equal columns or rows.repeat(auto-fill, minmax(100px, 1fr)): fills container with as many columns as fit.- Use with
grid-template-columnsorgrid-template-rows.
Key Takeaways
Use
repeat(count, size) to create repeated grid tracks easily.The
count must be a positive number or auto-fill/auto-fit for dynamic layouts.Combine
repeat() with flexible units like fr for responsive grids.Avoid mixing incompatible units inside
repeat() to prevent layout issues.Use
repeat() in grid-template-columns or grid-template-rows for cleaner code.