CSS
Dynamic Grid Columns with `auto-fit` and `minmax`
Create responsive, self-adapting grid layouts where columns automatically adjust to fill available space using `grid-template-columns` with `auto-fit` and `minmax`.
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
padding: 10px;
border: 1px solid #ccc;
}
.grid-item {
background-color: #d1ecf1;
padding: 20px;
border: 1px solid #add8e6;
text-align: center;
}
/* HTML Structure Example: */
/* <div class="grid-container">
/* <div class="grid-item">Item 1</div>
/* <div class="grid-item">Item 2</div>
/* <div class="grid-item">Item 3</div>
/* <div class="grid-item">Item 4</div>
/* <div class="grid-item">Item 5</div>
/* </div> */
How it works: This CSS Grid snippet creates a dynamic grid where columns automatically adjust to fill the available space. `repeat(auto-fit, minmax(200px, 1fr))` instructs the grid to create as many columns as can fit, each with a minimum width of 200px and a maximum width that takes up an equal share of the remaining space. `auto-fit` smartly collapses any empty tracks, preventing unwanted gaps when there aren't enough items to fill every potential column.