CSS
Dynamic Responsive Grids with auto-fit and minmax
Create self-adapting, responsive grid layouts where columns automatically adjust based on available space and a defined minimum width using `grid-template-columns`.
.grid-container {
display: grid;
/* auto-fit: fills the row with items, expanding them if needed */
/* minmax(200px, 1fr): items are at least 200px, but grow to fill available space equally */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1.5em; /* Spacing between grid items */
padding: 1.5em;
max-width: 1200px;
margin: 0 auto; /* Center the grid on the page */
background-color: #f7f7f7;
border: 2px dashed #ddd;
}
.grid-item {
background-color: #a7d9f2;
border: 1px solid #7cbcdb;
padding: 1.5em;
text-align: center;
color: #333;
font-size: 1.1em;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
How it works: This snippet creates a highly flexible and responsive grid layout. The `grid-template-columns` property uses `repeat(auto-fit, minmax(200px, 1fr))` to instruct the grid to automatically create as many columns as can fit within the container. Each column will be at least `200px` wide, but will grow to share available space equally (`1fr`) if there's extra room. `auto-fit` will expand items to fill any empty track space if there aren't enough items to fill all generated slots, making it ideal for dynamic content.