87. Responsive Grid with auto-fit and minmax()
CSS Grid provides an incredibly elegant solution for creating responsive, self-adjusting card or gallery layouts without using a single media query. This is achieved using the repeat() function combined with minmax() and auto-fit.
The Self-Adjusting Column Formula
We define the columns based on a minimum desirable size, allowing the browser to calculate how many columns fit on the screen and adjust the width of those columns to fill the space.
css .responsive-gallery { display: grid; gap: 1.5rem;
grid-template-columns: repeat( auto-fit, minmax(300px, 1fr) /* Min size is 300px, max size is 1 fraction */ ); }
Breakdown
repeat(...): Defines a repeating pattern for the columns.auto-fit: Tells the browser to calculate how many columns of the specified size can fit on the current screen.minmax(300px, 1fr):- If the available space allows for three 300px columns, the browser creates three columns.
- The
1frensures that any leftover space (e.g., 50px) is equally distributed across those columns, making them wider than 300px. - If the screen shrinks and only two columns fit, those two columns will expand to fill 100% of the container width until they hit the 300px floor, then they start wrapping or shrinking (due to the
1fr).
auto-fill vs. auto-fit: auto-fill creates empty tracks if space is available. auto-fit collapses empty tracks, allowing the items to expand fully. auto-fit is usually preferred for item-based layouts.