CSS
Responsive CSS Grid with auto-fit and minmax()
Create a highly responsive grid that automatically adjusts the number of columns and item sizes using `grid-template-columns`, `auto-fit`, and `minmax()` for dynamic layouts.
.grid-container {
display: grid;
/* auto-fit will expand items to fill available space if there are fewer items than max columns */
/* auto-fill would maintain fixed column count, leaving empty space */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px; /* Space between grid items */
padding: 20px;
}
.grid-item {
background-color: #e0f2f7;
border: 1px solid #a7d9ed;
padding: 15px;
text-align: center;
min-height: 100px;
}
How it works: This powerful snippet creates a responsive grid where the number of columns adapts dynamically based on the viewport size. `repeat(auto-fit, minmax(200px, 1fr))` ensures each column is at least `200px` wide but can grow (`1fr`) to fill available space. `auto-fit` will allow items to stretch and consume any leftover space if there are fewer items than maximum possible columns, while `gap` provides consistent spacing between grid items.