CSS
Create a Responsive CSS Grid with Auto-Fitting Columns
Build flexible, responsive grid layouts that automatically adjust column count and width based on screen size, using `grid-template-columns` with `auto-fit` and `minmax` for dynamic layouts.
.grid-container {
display: grid;
/* Defines columns that auto-fit, ensuring at least 200px width */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px; /* Spacing between grid items */
padding: 20px;
max-width: 1200px;
margin: 0 auto;
border: 2px dashed #ccc;
}
.grid-item {
background-color: #e0ffe0;
padding: 20px;
border: 1px solid #90ee90;
text-align: center;
}
How it works: This snippet showcases how to create a highly flexible and responsive grid layout using CSS Grid. `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))` is the key. `auto-fit` tells the grid to create as many columns as can fit into the container, while `minmax(200px, 1fr)` ensures each column is at least 200px wide but can grow to fill available space equally. The `gap` property provides consistent spacing between grid items, making it perfect for responsive card layouts or galleries.