CSS
Flexible Responsive Grid with Dynamic Columns using `auto-fit` and `minmax`
Build a highly flexible and responsive grid with CSS Grid's `auto-fit` and `minmax`. Dynamically adjusts column count based on viewport and item width, minimizing media query use.
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
/* `auto-fit` or `auto-fill` combined with `minmax` is key */
gap: 1.5rem;
padding: 1rem;
max-width: 1200px;
margin: 0 auto;
}
.grid-item {
background-color: #e7f5ff;
border: 1px solid #a9daff;
padding: 20px;
text-align: center;
border-radius: 5px;
}
How it works: This snippet creates a dynamically responsive grid that adjusts the number of columns based on the available space and the minimum width of the items, without needing explicit media queries for column breaks. The magic lies in `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))`. `auto-fit` (or `auto-fill`) allows the grid to create as many columns as can fit, `minmax(250px, 1fr)` ensures each column is at least 250px wide but can grow to take up an equal fraction of the remaining space (`1fr`). This combination results in a highly flexible grid that reflows naturally across different screen sizes.