CSS
Create Responsive, Auto-Sizing Grid Columns with minmax() and auto-fit
Design dynamic grid layouts that automatically adjust the number and width of columns based on available space and content using `grid-template-columns`, `minmax()`, and `auto-fit`.
/* HTML Structure */
/*
<div class="responsive-grid">
<div class="grid-item">Item 1</div>
<div class="grid-item">Item 2 with more content</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
<div class="grid-item">Item 5</div>
<div class="grid-item">Item 6</div>
</div>
*/
/* CSS */
.responsive-grid {
display: grid;
gap: 15px;
/*
repeat(auto-fit, minmax(200px, 1fr)):
- `auto-fit` will fit as many columns as possible on one row.
- `minmax(200px, 1fr)` specifies that each column should be at least 200px wide,
but no larger than 1 fraction of the available space. This makes them expand
to fill the row if there's extra space.
- Use `auto-fill` instead of `auto-fit` if you want to leave empty tracks
when there aren't enough items to fill the row (e.g., for placeholders).
*/
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
padding: 20px;
background-color: #e0f2f7;
}
.grid-item {
background-color: #a7d9ee;
border: 1px solid #7cb1c2;
padding: 1rem;
text-align: center;
color: #333;
border-radius: 5px;
}
How it works: This snippet demonstrates a powerful technique for creating responsive grids where columns automatically adjust. `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))` is the key. `auto-fit` (or `auto-fill`) tells the grid to create as many columns as can fit. `minmax(200px, 1fr)` ensures that each column is at least 200 pixels wide, but can grow to take up an equal fraction (`1fr`) of the remaining space. This creates a highly adaptable layout where items arrange themselves into optimal columns across different screen sizes.