CSS
Responsive Grid Layouts with Auto-Adjusting Columns
Master creating responsive CSS Grid layouts where the number of columns dynamically adjusts based on available space using `repeat()`, `auto-fit`, and `minmax()` functions.
.grid-container {
display: grid;
/* auto-fit or auto-fill creates as many columns as possible */
/* minmax(250px, 1fr) ensures columns are at least 250px wide, */
/* but can grow to fill space (1fr) if larger than 250px */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
background-color: #f0f0f0;
}
.grid-item {
background-color: #28a745;
color: white;
padding: 30px;
text-align: center;
font-size: 1.2em;
border-radius: 5px;
}
How it works: This code snippet illustrates how to build highly responsive grid layouts using CSS Grid's `repeat()`, `auto-fit`, and `minmax()` functions. `repeat(auto-fit, minmax(250px, 1fr))` tells the browser to create as many columns as can fit, ensuring each column is at least `250px` wide but can expand up to `1fr` (an equal fraction of the remaining space). `auto-fit` will collapse empty tracks, making it ideal for dynamic content counts, while `auto-fill` would create empty tracks even if no items fill them.