tezvyn:

CSS Grid: auto-fit vs. auto-fill

AI-drafted, machine-checkedSource: developer.mozilla.orgadvanced
CSS Grid: auto-fit vs. auto-fill

Create responsive grids without media queries. `auto-fill` creates as many columns as fit, leaving empty ones. `auto-fit` collapses empty columns, letting content stretch to fill the space. The footgun is using `auto-fill` when you want items to grow.

WHY IT EXISTS To create responsive layouts without writing dozens of media queries. Before this, making a grid of items wrap and resize gracefully required complex breakpoints to change column counts. The repeat() function with auto-fit or auto-fill lets the browser automatically calculate how many columns can fit in a container.

THE MENTAL MODEL Think of auto-fill as a parking lot with a fixed number of painted spots. It creates as many spots (grid tracks) as can fit. Even if cars don't park in all of them, the empty spots still exist and take up space. auto-fit is like a valet service: it also creates spots, but if there's extra room, it collapses the empty spots and lets the parked cars expand to fill the newly available space (if they're defined with flexible units).

HOW IT WORKS Both auto-fill and auto-fit are keywords used as the first argument in the repeat() function for grid-template-columns. They calculate how many columns of a given size can fit into the container's width. auto-fill creates as many tracks as possible, even if they end up empty. auto-fit also creates as many tracks as can fit, but it collapses any empty tracks to 0px, allowing the non-empty tracks to grow and consume the available space if defined with a flexible unit like 1fr.

WHEN TO USE IT Use auto-fit when you have a variable number of items and you want them to stretch and fill the container's width on rows that aren't full. This is the most common use case for responsive card galleries. Use auto-fill if you need to maintain a consistent grid alignment even with few items, or for debugging to visualize the empty tracks the browser creates.

WHEN NOT TO USE IT Don't use these keywords if you need a fixed number of columns regardless of viewport size; use an integer like repeat(4, 1fr) instead. Avoid auto-fill when your goal is to have items grow to fill leftover space, as the invisible empty tracks will prevent this behavior.

ONE CANONICAL EXAMPLE The most powerful pattern is grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));. This tells the browser: create as many columns as you can that are at least 250px wide. If there's leftover space on a row, collapse any empty columns and distribute that extra space among the items on that row, making them grow. This single line of CSS creates a fully responsive grid.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.