Emmanuel Akinfulubi

HTML and CSSPractical II

Responsive card grid without media queries in CSS

22 A card grid with no breakpoints

fair

Lay cards out in as many columns as the space allows, with no media queries. Then say precisely how auto-fit differs from auto-fill.

Stuck? Three hints, smallest first
  1. 1. repeat(auto-fit, minmax(140px, 1fr)) is the whole declaration.
  2. 2. auto-fill keeps the empty tracks it created; auto-fit collapses them so the items stretch.
  3. 3. The difference is only visible when there are fewer items than tracks.

index.html

<ul class="grid">
  <li>Abuja</li>
  <li>Kano</li>
  <li>Enugu</li>
  <li>Ibadan</li>
  <li>Benin</li>
</ul>

style.css

.grid {
  display: grid;
  /* As many 140px columns as fit; each then shares out the leftover space. */
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 10px;
  margin: 0;
  padding: 0;
  list-style: none;
}

.grid li {
  padding: 14px 12px;
  background: #eef1fd;
  border: 1px solid #3055d8;
  border-radius: 8px;
  text-align: center;
  font-size: 0.85rem;
}
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 22

// How many tracks fit, given a container width, a track minimum and a gap.
const fits = (container, min, gap) =>
  Math.max(1, Math.floor((container + gap) / (min + gap)));

test('at 480px wide, with a 140px minimum and a 10px gap, three fit', fits(480, 140, 10), 3);
test('at 300px, two fit', fits(300, 140, 10), 2);
test('at 120px it never drops below one', fits(120, 140, 10), 1);
test('the declaration uses auto-fit', /repeat\(\s*auto-fit/.test(css), true);
test('with a floor and a share of the surplus', /minmax\(\s*140px\s*,\s*1fr\s*\)/.test(css), true);
test('no media query anywhere', /@media/.test(css), false);
test('five cards, in a real list', countTag(html, 'li') === 5 && hasTag(html, 'ul'), true);
test('spaced with gap rather than margins', /gap:\s*10px/.test(css), true);

Output


      

The arithmetic in the first three checks is what the browser does for you, and it is worth seeing written down: the container width plus one gap, divided by a track plus one gap. That is why no breakpoint is needed — the layout responds to the width it actually has. The auto-fit versus auto-fill difference only shows with fewer items than tracks: auto-fill leaves the empty columns in place, so two cards stay narrow at the left, while auto-fit collapses them so the two stretch across. Neither is wrong; they answer different questions.

Newsletter

New writing, when it lands.

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