CSS
Create Responsive Grids with `repeat`, `minmax`, and `auto-fit`
Build adaptive and fluid grid layouts that automatically adjust column count and width based on available space using CSS Grid's powerful `repeat`, `minmax`, and `auto-fit` functions.
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
max-width: 1200px; /* Example constraint */
margin: 0 auto;
}
.grid-item {
background-color: #f0f0f0;
border: 1px solid #ddd;
padding: 30px;
text-align: center;
}
/* HTML Context */
/*
<div class="grid-container">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
<div class="grid-item">Item 5</div>
<div class="grid-item">Item 6</div>
</div>
*/
How it works: The `grid-template-columns` property is set to `repeat(auto-fit, minmax(250px, 1fr))`. `auto-fit` automatically creates as many columns as can fit while respecting the `minmax` function. `minmax(250px, 1fr)` ensures each column is at least 250px wide but can grow to fill available space equally (`1fr`). `gap` adds spacing between grid items.