CSS
Build Responsive Grids with `grid-template-columns` and `minmax`
Learn to create flexible, responsive CSS Grid layouts that adapt to any screen size using `grid-template-columns`, `repeat`, `minmax`, and `auto-fit` for dynamic content.
.responsive-grid-container {
display: grid;
/*
* auto-fit: Fills the available space, collapsing empty tracks if items don't fill a row.
* auto-fill: Fills the available space, but keeps empty tracks, ensuring all columns are present.
* repeat(auto-fit, minmax(min-width, max-width)): Creates as many columns as fit,
* where each column is at least min-width and no more than max-width (1fr distributes remaining space).
*/
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px; /* Spacing between grid items */
padding: 20px;
}
.grid-item {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
padding: 15px;
text-align: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
How it works: This snippet illustrates how to create a highly responsive grid layout using CSS Grid's powerful `grid-template-columns` property. By combining `repeat(auto-fit, minmax(250px, 1fr))`, the grid automatically adjusts the number of columns based on the available viewport width. Each column will be at least 250px wide, and will grow up to `1fr` (one fraction of the available space) when there's more room. The `gap` property ensures consistent spacing between grid items, making it ideal for product listings, image galleries, or card layouts.