Use auto-fill inside repeat() to create as many CSS Grid tracks as fit the available space. Unlike auto-fit, it preserves empty tracks at their calculated size. section 4.4.4 section 4.6
The browser estimates the repetition count by subtracting grid gaps from the container width, dividing by the repeated track width, and rounding down: num_repetitions = floor((container_width - sum_of_gaps) / track_width). section 4.4.4
Four 100px columns in a 450px grid
With a 450px container, 10px gaps, and 100px tracks, the calculation produces four repetitions. auto-fill keeps all four columns, even when some remain empty. section 4.4.4
Listing 4.10 Demonstrating the difference between auto-fill and auto-fit
<head>
<style>
.grid-container {
display: grid;
gap: 1rem;
grid-auto-rows: 100px;
width: 850px
}
.auto-fill-grid {
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
.auto-fit-grid {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
</style>
</head>
<body>
<div class="grid-container auto-fill-grid">
<div class="card">Item A</div>
<div class="card">Item B</div>
</div>
<div class="grid-container auto-fit-grid">
<div class="card">Item A</div>
<div class="card">Item B</div>
</div>
</body>
Compare two 850px grids containing only two cards: auto-fill retains empty columns, while auto-fit collapses them and lets occupied tracks expand. section 4.4.4
Choose auto-fill when the grid should preserve its calculated structure:
- Define repeated tracks with syntax such as repeat(auto-fill, 100px) or repeat(auto-fill, minmax(200px, 1fr)). section 4.4.4
- Expect empty tracks to retain their size rather than collapsing and redistributing space. section 4.4.4

