What Is CSS repeat(auto-fit, minmax()) Used For?
The CSS repeat(auto-fit, minmax(...)) pattern is a
responsive design technique that automatically calculates and adjusts
grid columns based on available container space without requiring CSS
media queries. By combining track repetition with dynamic minimum and
maximum boundaries, this pattern allows child elements to wrap, shrink,
and expand smoothly across all screen sizes, creating fluid multi-column
card grids, product lists, and galleries.
Anatomy of the Pattern
To understand how the pattern functions as a whole, it helps to examine its core CSS Grid components:
grid-template-columns: The property that defines the number and widths of columns in a grid container.repeat(): A CSS Grid function that repeats a track pattern a specified number of times or dynamically based on available space.auto-fit: A keyword passed torepeat()that fills the row with as many columns as will fit, then collapses any empty tracks to zero width so the remaining items stretch to take up the full row width.minmax(min, max): A sizing function that sets a hard lower boundary (min) below which a track cannot shrink, and an upper boundary (max) that determines how much space a track can occupy when room permits.
Standard Implementation
The standard implementation pairs a fixed minimum size (such as
250px or 15rem) with a fractional unit
(1fr) for the maximum limit:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
}In this setup:
- The browser checks the total width of
.grid-container. - It calculates how many
250pxtracks can fit along the row while accounting for the1.5remgap. - If there is leftover horizontal space, the
1frmaximum value distributes that remaining space equally across the existing columns. - When the viewport narrows and a column cannot maintain its
250pxminimum, the grid wraps that item to a new line and expands the remaining items to fill the previous row.
auto-fit vs.
auto-fill
While both keywords create dynamic tracks, they handle surplus row space differently when there are fewer items than the container can hold:
auto-fit: Collapses any empty tracks to0px, allowing the active items to stretch across the full width of the container. This makes it ideal for standard card layouts where content should always look balanced.auto-fill: Preserves empty grid tracks even if there are no items to populate them, keeping existing items at their minimum defined size rather than stretching them.
Common Use Cases
- Responsive Product Galleries: E-commerce grids where product cards need to reflow naturally from desktop monitors to mobile displays.
- Dashboard Widgets: Flexible UI tiles that resize proportionally as sidebars toggle or window sizes shift.
- Media and Image Lists: Visual feeds where uniform item wrapping and proportional scaling are required without breaking layout boundaries.