Sub topic 7
Responsive columns with auto-fit
This chapter assumes you can write a grid container with display: grid, size tracks with fr units and gap, and use repeat() and minmax() in grid-template-columns. It also assumes basic familiarity with media queries. Here you will build a card grid whose column count changes with the container's width, with no media queries.
The problem with fixed column counts
A fixed template such as repeat(3, 1fr) always makes three columns. On a 320px phone, each column is about 100px wide, which is too narrow for most cards. The usual fix is a media query that drops to two columns, then to one, with breakpoints you must choose and maintain.
auto-fit reverses the approach. You state the narrowest acceptable column, and the browser works out how many of those columns fit.
The core pattern
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}Read the declaration from the inside out:
minmax(200px, 1fr)describes one column. It is never narrower than 200px, and it can grow to a share of the free space.repeat(auto-fit, ...)repeats that column as many times as the container can hold.gapis subtracted from the available width before columns are counted.
Here is a complete page you can save and open in a browser. Resize the window and watch the columns change.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Auto-fit cards</title>
<style>
body { font-family: system-ui, sans-serif; margin: 1rem; }
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.card {
padding: 1rem;
border: 1px solid #888;
border-radius: 0.5rem;
background: #f4f4f8;
}
</style>
</head>
<body>
<div class="cards">
<div class="card">One</div>
<div class="card">Two</div>
<div class="card">Three</div>
<div class="card">Four</div>
<div class="card">Five</div>
<div class="card">Six</div>
<div class="card">Seven</div>
</div>
</body>
</html>With seven cards and a wide window, the cards fill the first row and the rest wrap onto a second row. The columns stay aligned in both rows, because the grid has one set of column tracks shared by every row.
How the browser picks the column count
The browser needs to know how many repetitions fit. It takes the container's content width, then packs in as many tracks as it can, using the minimum size of each track (200px here) and adding the gaps between them. The count is the largest whole number n that satisfies this:
n * min + (n - 1) * gap <= container widthSolving for n gives n = floor((width + gap) / (min + gap)), with a floor of 1. After choosing n, the browser gives each column an equal share of the width left over once the gaps are removed. The 1fr maximum is what allows this stretching.
The table below uses a 200px minimum and a 16px gap (1rem at the default font size).
| Container width | Columns (n) | Width of each column |
|---|---|---|
| 320px | 1 | 320px |
| 450px | 2 | 217px |
| 700px | 3 | about 222.7px |
| 900px | 4 | 213px |
| 1200px | 5 | about 227.2px |
Each column width is (width - (n - 1) * gap) / n. Every column is at least 200px, but the actual width drifts between 200px and just under 2 × 200px as the container resizes. Right before a new column fits, the columns are at their widest. The moment it fits, they all shrink to make room.
Why the maximum must be flexible
The second argument of minmax() controls what happens to leftover space.
| Track definition | Result |
|---|---|
| `minmax(200px, 1fr)` | Columns stretch and fill the row exactly. |
| `minmax(200px, 300px)` | Columns stop growing at 300px, so wide containers show unused space at the end of the row. |
| `200px` | Columns are always 200px, and leftover space remains unused. |
Most card layouts want the first form, because a ragged right edge looks like a bug. If you do want fixed-width cards, use a fixed maximum and set justify-content: center on the container so the leftover space splits evenly on both sides.
Rules for auto repetition
auto-fit and auto-fill are the two keywords that make an auto repetition. They have constraints that the browser enforces when it parses the declaration.
- The repeated tracks must have a definite size.
repeat(auto-fit, 1fr)is invalid, because the browser cannot count how many 1fr tracks fit.minmax(200px, 1fr)is valid because its minimum is a fixed length. - You can use only one auto repetition in a template.
- You can mix fixed tracks with the repeat. For example,
grid-template-columns: 240px repeat(auto-fit, minmax(160px, 1fr));reserves a 240px first column and fills the rest. Count the fixed track and its gap when you reason about how many columns fit. - An invalid
grid-template-columnsvalue is dropped as a whole. The grid then falls back to a single implicit column, so you will see a single stacked column rather than an error.
Controlling the minimum width
Choosing the minimum is the only real design decision in this pattern. It sets the narrowest card you will accept, and the container width and gap decide everything else. You can express it with any length unit.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
gap: 1.5rem;
}Using rem makes the minimum scale with the user's font size, so people who raise their default text size get fewer, wider columns instead of cramped ones. A pixel minimum does not respond to that setting.
Percentages in the minimum are risky. A percentage inside minmax() resolves against the container, which makes the count depend on itself in confusing ways. Prefer px, rem, or ch.
Rows and item sizing
auto-fit only affects columns. Rows are created implicitly as items wrap, and they are sized by grid-auto-rows, which defaults to auto. Each row grows to fit its tallest card. If you want every row to have a minimum height, set it explicitly:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: minmax(8rem, auto);
gap: 1rem;
}Items in the same row stretch to the same height by default (align-items: stretch), which is why a short card sits level with a tall neighbor.
Common mistakes
- Width constraints on the cards. A
widthormax-widthon.cardfights the track sizes. Let the grid size the cards. - Using margins instead of
gap. Margins on cards are not subtracted when the column count is computed, so the layout either overflows or leaves odd spaces. Usegap. - Expecting content to push the count. The count comes from the container and the minimum. A long word inside a card does not reduce the number of columns, though it can make a track wider than its minimum. Add
overflow-wrap: anywhereormin-width: 0on the card content when long strings are possible. - A container with no definite width. If the grid sits in a shrink-to-fit parent, such as a floated element or an inline-block, the available width depends on the grid's own content. Give the parent a real width, or let it be a normal block.
- Narrow containers. If the container is narrower than the minimum, one column is created and it overflows. The chapter on preventing overflow covers the fix with
min().
Seeing the effect in the browser
Open the developer tools, select the .cards element, and turn on the grid overlay (the "grid" badge next to the element in the Elements panel in most browsers). The overlay draws the track lines. Resize the window and note how the number of tracks changes at the widths from the table above. With only two or three cards in a wide container, you will also see what happens to empty tracks, which the next chapter compares for auto-fit and auto-fill.
Exercise
A container is 760px wide and uses grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px;. How many columns does it create, and how wide is each one?
Show answer
n = floor((760 + 20) / (180 + 20)) = floor(780 / 200) = 3 columns. The gaps total 2 × 20px = 40px, so each column is (760 - 40) / 3 = 240px wide.
Exercise
A developer writes grid-template-columns: repeat(auto-fit, minmax(1fr, 200px)); and sees all cards in one column. Why, and how do they fix it?
Show answer
The minimum of a minmax() cannot be an fr value, so the declaration is invalid and the browser discards it, leaving a single implicit column. The fix is to swap the arguments: repeat(auto-fit, minmax(200px, 1fr)).
Exercise
You want cards that never grow beyond 300px, centered in the row when there is spare space. Which two declarations on the container do this, given a 200px minimum?
Show answer
Use grid-template-columns: repeat(auto-fit, minmax(200px, 300px)); so the maximum is fixed, and justify-content: center; so the leftover horizontal space is split on both sides of the tracks.