Emmanuel Akinfulubi

HTML and CSSPractical I

Auto-fit responsive grid columns in CSS

2 A grid that fits as many columns as will go

fair

Lay cards out in columns that reflow on their own as the width changes, without writing any media queries.

Stuck? Three hints, smallest first
  1. 1. repeat(auto-fill, minmax(140px, 1fr)) is the whole trick.
  2. 2. auto-fill keeps empty tracks; auto-fit collapses them. That difference shows when there are few items.
  3. 3. minmax sets the smallest a column may be and lets it grow to share the space.

index.html

<ul class="cards">
  <li>Lagos</li>
  <li>Abuja</li>
  <li>Kano</li>
  <li>Enugu</li>
  <li>Ibadan</li>
</ul>

style.css

.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;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
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.

Checks for exercise 2

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.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.