CSS
CSS Grid: Dynamic Track Sizing with `repeat()` and `minmax()`
Master CSS Grid's `repeat()` and `minmax()` functions to create responsive and flexible column/row tracks that adapt to content and viewport size.
.grid-container {
display: grid;
/* Create columns that are at least 200px wide, but grow up to 1 fraction unit */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
padding: 20px;
background-color: #eef;
}
.grid-item {
background-color: #add8e6;
border: 1px solid #90caf9;
padding: 15px;
text-align: center;
min-height: 100px;
}
@media (max-width: 600px) {
.grid-container {
/* On smaller screens, allow columns to be smaller, min 150px */
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}
}
How it works: This snippet showcases the power of `repeat()`, `auto-fit`, and `minmax()` in CSS Grid for creating highly dynamic and responsive layouts. `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))` tells the grid to create as many columns as can fit, where each column is at least `200px` wide but can grow up to `1fr` (one fraction of the available space). This ensures items always have a minimum width while distributing extra space evenly. The media query demonstrates how to adjust the `minmax()` value for different screen sizes, providing fine-grained control over responsiveness.