Auto-fit responsive grid columns in CSS
2 A grid that fits as many columns as will go
fairLay cards out in columns that reflow on their own as the width changes, without writing any media queries.
Stuck? Three hints, smallest first
- 1.
repeat(auto-fill, minmax(140px, 1fr))is the whole trick. - 2.
auto-fillkeeps empty tracks;auto-fitcollapses them. That difference shows when there are few items. - 3.
minmaxsets the smallest a column may be and lets it grow to share the space.
<ul class="cards">
<li>Lagos</li>
<li>Abuja</li>
<li>Kano</li>
<li>Enugu</li>
<li>Ibadan</li>
</ul>
.cards {
display: grid;
/* As many 140px columns as fit; each then shares the leftover space. */
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 10px;
margin: 0;
padding: 0;
list-style: none;
}
.cards li {
padding: 14px;
background: #f2f3f5;
border-radius: 6px;
text-align: center;
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('it is a grid', declares(css, 'display', 'grid'), true);
test('the columns repeat automatically', /repeat\(\s*auto-fill/.test(css), true);
test('each column has a floor and can grow', /minmax\(\s*140px\s*,\s*1fr\s*\)/.test(css), true);
test('there is a gap rather than margins', declares(css, 'gap', '10px'), true);
test('no media query was needed', /@media/.test(css), false);
test('five cards', countTag(html, 'li'), 5);
test('the list markers are removed', declares(css, 'list-style', 'none'), true);
test('a list is used, because it is a list', hasTag(html, 'ul'), true);
Output
The fifth assertion is the point: this reflows at every width with no @media at all, because the browser is doing the arithmetic. Swap auto-fill for auto-fit and, with only two cards, they stretch to fill the row instead of leaving empty tracks — that is the entire difference between the two, and it only shows when the items are fewer than the columns.