Master CSS Grid's auto-placement features including auto-fit, auto-fill, minmax(), grid-auto-flow, and implicit grid tracks to create truly responsive grids without media queries.
The real power of CSS Grid for responsive design lies in the repeat() function combined with auto-fit or auto-fill and minmax(). This lets the browser automatically determine how many columns fit in the available space.
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}Breaking this down:
repeat() — Repeats a track pattern.auto-fit — Creates as many columns as will fit, and collapses empty tracks so items stretch to fill the row.auto-fill — Creates as many columns as will fit, but preserves empty tracks. Items do not stretch into empty columns.minmax(200px, 1fr) — Each column is at least 200px but can grow to take an equal share of leftover space.The difference between auto-fit and auto-fill only matters when you have fewer items than available columns. With auto-fit, excess columns collapse and items stretch. With auto-fill, empty columns remain, and items stay at their minimum size.
<style>
.auto-fit-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
gap: 8px;
margin-bottom: 16px;
background: #0f172a;
padding: 8px;
}
.auto-fill-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 8px;
background: #0f172a;
padding: 8px;
}
.item {
background: #6366f1;
padding: 16px;
text-align: center;
color: white;
border-radius: 4px;
}
</style>
<p>auto-fit (items stretch):</p>
<div class="auto-fit-grid">
<div class="item">1</div>
<div class="item">2</div>
</div>
<p>auto-fill (empty tracks preserved):</p>
<div class="auto-fill-grid">
<div class="item">1</div>
<div class="item">2</div>
</div>When you place more items than your explicit grid definition accounts for, CSS Grid creates implicit tracks to hold the extra items. You can control the size of these implicit tracks:
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 150px; /* implicit rows are 150px */
}The grid-auto-flow property controls how auto-placed items fill the grid:
row (default) — Items fill each row before moving to the next.column — Items fill each column before moving to the next.dense — The browser tries to fill in holes earlier in the grid. Add it after row or column: grid-auto-flow: row dense..gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: dense; /* fill gaps */
}
.gallery .wide {
grid-column: span 2; /* some items span 2 columns */
}Dense packing is great for image galleries where visual order does not need to match source order. However, avoid it for content where reading order matters, as it can reorder items visually.
What is the difference between auto-fit and auto-fill when there are fewer items than available columns?