CSS
Responsive Grid with Auto-Adjusting Columns
Create a dynamic, responsive grid layout that automatically adjusts the number of columns based on available space using CSS Grid's `minmax` and `auto-fit` functions.
.grid-container {
display: grid;
/* Automatically adjust columns: minimum 250px, maximum 1 fraction of available space */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px; /* Space between grid items */
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.grid-item {
background-color: #e0f2f7;
border: 1px solid #a7d9ed;
padding: 15px;
text-align: center;
}
How it works: This CSS Grid snippet creates a highly responsive layout where the number of columns adjusts automatically based on the viewport width. `display: grid` initializes the grid. `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))` is the core: `auto-fit` creates as many columns as can fit, each being at least `250px` wide but growing up to `1fr` (one fraction of the remaining space) if more space is available. `gap` defines the spacing between grid items.