CSS
Creating a Responsive Auto-Fitting Grid Layout
Build dynamic, responsive grids that automatically adjust the number of columns based on available viewport space using CSS Grid's powerful `repeat(auto-fit, minmax())` function.
/* Responsive Grid Container */
.responsive-grid {
display: grid;
/*
* `auto-fit`: Fills the row with as many columns as possible.
* Empty tracks at the end of the row will collapse.
* `minmax(250px, 1fr)`: Each column will be at least 250px wide.
* If there's extra space, it will grow to fill it (1fr).
*/
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem; /* Space between grid items */
padding: 1rem;
max-width: 1200px; /* Example max width */
margin: 0 auto;
background-color: #f0f0f0;
}
.grid-item {
background-color: #fff;
border: 1px solid #ddd;
padding: 1.5rem;
text-align: center;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
How it works: This snippet provides a robust solution for creating responsive grid layouts that adapt fluidly to different screen sizes. By using `display: grid;` and `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));`, the grid automatically creates as many columns as can fit while ensuring each column is at least `250px` wide. If there's more space, columns will grow proportionally (`1fr`). The `gap` property maintains consistent spacing between items, making it perfect for card layouts, image galleries, and more.