Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 2

Grid for Pages and Card Collections

Lay out a whole page shell with named areas, fill a card collection with repeat(), minmax() and auto-fit, and align card internals with subgrid.

Contentsand lesson path

What you will learn

  • Build two-dimensional page and component layouts with CSS grid, including named areas, minmax(), auto-fit and subgrid.

Prerequisites: CSS Cascade & Box Model

01. The problem

Where flexbox arranges items along one axis, grid is built for two dimensions at once: rows and columns that belong to a shared plan. That makes it the natural tool for two jobs. First, the page shell, a header, a filters column, a main area and a footer whose edges must line up. Second, the card collection, a set of equal slots that reflows as the window narrows.

This lesson builds both, then fixes a problem flexbox could not solve cleanly: cards in one row whose titles and buttons line up with each other. As in the previous lesson, every claim is checked with a measurement script at the end, so the numbers are real browser output. The pages reuse the styles pattern from the flexbox lesson; the box model basics live in /skills/css-fundamentals.

HTML · index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Grid layouts</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div class="page">
      <header class="head">Site header</header>
      <nav class="side" aria-label="Filters">Filters</nav>
      <main class="main">Main</main>
      <footer class="foot">Footer</footer>
    </div>

    <section class="cards fill" aria-label="Auto-fill grid">
      <article class="card">Card 1</article>
      <article class="card">Card 2</article>
      <article class="card">Card 3</article>
      <article class="card">Card 4</article>
      <article class="card">Card 5</article>
      <article class="card">Card 6</article>
    </section>

    <section class="cards fit" aria-label="Auto-fit grid with two cards">
      <article class="card">Card 1</article>
      <article class="card">Card 2</article>
    </section>
HTML · index.html (continued)
    <section class="cards sub" aria-label="Cards sharing row tracks">
      <article class="card">
        <h2>First</h2>
        <p>Short body.</p>
        <button type="button" class="buy">Buy</button>
      </article>
      <article class="card">
        <h2>Second card with a longer title</h2>
        <p>A body with more words in it.</p>
        <button type="button" class="buy">Buy</button>
      </article>
      <article class="card">
        <h2>Third</h2>
        <p>Much longer body so that its card is clearly the tallest of the three.</p>
        <button type="button" class="buy">Buy</button>
      </article>
    </section>

    <section class="cards plain" aria-label="Cards with independent rows">
      <article class="card">
        <h2>First</h2>
        <p>Short body.</p>
        <button type="button" class="buy">Buy</button>
      </article>
      <article class="card">
        <h2>Second card with a longer title</h2>
        <p>A body with more words in it.</p>
        <button type="button" class="buy">Buy</button>
      </article>
      <article class="card">
        <h2>Third</h2>
        <p>Much longer body so that its card is clearly the tallest of the three.</p>
        <button type="button" class="buy">Buy</button>
      </article>
    </section>
  </body>
</html>

02. Step 1: a page shell with named areas

CSS · styles.css
* {
  box-sizing: border-box;
}

body {
  font: 16px/1.5 system-ui, sans-serif;
  margin: 0;
  padding: 16px;
}

.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    'head head'
    'side main'
    'foot foot';
  gap: 16px;
  min-height: 320px;
}

.page > * {
  border: 1px solid #666;
  border-radius: 8px;
  padding: 12px;
}

.head { grid-area: head; }
.side { grid-area: side; }
.main { grid-area: main; }
.foot { grid-area: foot; }

@media (max-width: 47.99em) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas:
      'head'
      'side'
      'main'
      'foot';
  }
}

Each quoted string in grid-template-areas is one row, and each word in it is one cell. Repeating a name spans an area across cells, which is why head head gives the header both columns and foot foot does the same for the footer. Every row must contain the same number of cells, or the browser drops the whole declaration. Each child then claims its place with grid-area: <name>, so the CSS reads like a picture of the page.

Measured at a 900px viewport: the filters column sits at x = 16 and is 240px wide, the main area starts at x = 272 (16px body padding + 240px + one 16px gap) and is 612px wide (868 − 240 − 16), and the footer spans the full 868px. Below 48em the media query redefines the areas to a single column, and the same elements stack: at 360px the filters start at y = 82 and the main area at y = 220. One grid, two layouts, no position hacks. The next lesson looks at media queries in their own right.

03. Step 2: a card collection that reflows itself

CSS · styles.css
.cards {
  display: grid;
  gap: 16px;
  margin-block: 16px;
}

.fill,
.fit {
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

.fit {
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

.card {
  border: 1px solid #666;
  border-radius: 8px;
  padding: 12px;
}

.card > * {
  margin: 0;
}

The repeat() with auto-fill does the responsive work without a single media query. The browser works out how many columns of at least 200px fit, then stretches them all to share the row. Measured on the .fill grid:

  • at 900px (868px of body width): 4 tracks of 205px, because (868 + 16) / (200 + 16) rounds down to 4;
  • at 700px: 3 tracks of 212px;
  • at 320px: 1 track of 288px.

Inside each track, minmax(200px, 1fr) means "never below 200px, otherwise share the free space equally", so tracks grow to fill the row instead of leaving a stubby remainder. On the card side, align-items: start on the grid keeps a short card from stretching to the height of its tallest neighbour; add it deliberately whenever cards should keep their own height.

04. Step 3: auto-fill or auto-fit

The .fit section holds only two cards, and that is where the two keywords part ways. At 900px the computed track list for auto-fit reads 426px 426px 0px 0px: the two empty tracks collapse to zero width and the real cards stretch into the space. With auto-fill the empty tracks would have kept their 205px, holding their place so a row of two cards never balloons across the page.

The rule of thumb falls out of the measurement. A catalogue that can shrink to one or two items after filtering usually wants auto-fill, so cards stay at a readable width. A hero band of feature tiles that always fills its row anyway often suits auto-fit, which avoids ever showing ghost columns. Neither keyword removes the tracks from the grid, as the computed 0px values show; they only change how empty ones are sized.

05. Step 4: line cards up with subgrid

CSS · styles.css
.sub,
.plain {
  grid-template-columns: repeat(3, 1fr);
}

.sub .card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid;
}

.plain .card {
  display: grid;
  gap: 8px;
}

Each .sub card spans three rows of the parent grid and declares those rows as its own with grid-template-rows: subgrid. Its title, body and button now sit in tracks shared with its neighbours, so the tallest title in the row stretches every card's title track, and all three Buy buttons land on the same line. Measured, the buttons sit at y = 739 in all three subgrid cards. The .plain cards, which each own their internal rows, put their buttons at y = 910, 922 and 926; close, because the demo text is short, but visibly not aligned.

One detail surprises people: how subgrid handles gaps. When a subgrid leaves gap unset (or sets gap: normal), it inherits the parent grid's row tracks and gaps, and the parent's row gap is 16px. Inside .sub, spacing between title, body and button is the parent's gap speaking through the shared tracks. Explicitly specifying a custom gap on the subgrid overrides the parent's gutter, whereas inheriting with normal lets parent and child negotiate over one set of rows and gutters seamlessly.

06. Measure the results

The script below produced every number quoted above. It reads the computed track list, which is the honest answer to "how many columns am I actually in?", and compares button positions to prove the alignment. Headless Chromium (via Playwright 1.64.1) again; your font stack may move a pixel here or there.

JavaScript · measure.mjs
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(pathToFileURL('index.html').href);

const tracksOf = (sel) =>
  page.$eval(sel, (el) => getComputedStyle(el).gridTemplateColumns);

const box = (sel) =>
  page.$eval(sel, (el) => {
    const r = el.getBoundingClientRect();
    return { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width) };
  });

for (const width of [900, 700, 320]) {
  await page.setViewportSize({ width, height: 900 });
  const tracks = await tracksOf('.fill');
  console.log(`${width}px auto-fill: ${tracks.split(' ').length} track(s): ${tracks}`);
}

await page.setViewportSize({ width: 900, height: 900 });
const fit = await tracksOf('.fit');
console.log(`900px auto-fit, 2 cards: ${fit}`);

const side = await box('.side');
const main = await box('.main');
const foot = await box('.foot');
console.log(
  `900px shell: filters x=${side.x} w=${side.w}, main x=${main.x} w=${main.w}, ` +
    `footer w=${foot.w}`,
);

await page.setViewportSize({ width: 360, height: 900 });
const sideN = await box('.side');
const mainN = await box('.main');
console.log(`360px shell: filters y=${sideN.y}, main y=${mainN.y}`);

await page.setViewportSize({ width: 900, height: 900 });
const buttonYs = (sel) =>
  page.$$eval(sel, (els) =>
    els.map((el) => Math.round(el.getBoundingClientRect().y)),
  );
const subYs = await buttonYs('.sub .buy');
const plainYs = await buttonYs('.plain .buy');
console.log(`900px Buy button y, subgrid:    ${subYs.join(' / ')}`);
console.log(`900px Buy button y, no subgrid: ${plainYs.join(' / ')}`);
await browser.close();
Illustrative output (Chromium 156 via Playwright 1.64.1; the y values depend on your fonts)
900px auto-fill: 4 track(s): 205px 205px 205px 205px
700px auto-fill: 3 track(s): 212px 212px 212px
320px auto-fill: 1 track(s): 288px
900px auto-fit, 2 cards: 426px 426px 0px 0px
900px shell: filters x=16 w=240, main x=272 w=612, footer w=868
360px shell: filters y=82, main y=220
900px Buy button y, subgrid:    739 / 739 / 739
900px Buy button y, no subgrid: 910 / 922 / 926

07. Check your understanding

Practice check · 3 questions

Reading a grid

Answer from the track rules this lesson measured.

Q1. A catalogue uses `repeat(auto-fill, minmax(200px, 1fr))` and shows six products. After filtering, two remain. What does the row look like now?
Q2. In a `grid-template-areas` value, what does a full stop (`.`) cell mean?
Q3. Cards use `grid-template-rows: subgrid` on a parent whose `gap` is 16px. The card's own rule says nothing about gap. How far apart are the card's title and body?
Practice only: not graded, not saved, not evidence.

08. Apply it

Bring grid into the product listing page from this skill's practice task:

  1. Replace the page shell with named areas: header, filters, products, footer, spanning full width above and below, side by side at 48em and above.
  2. Give the product collection repeat(auto-fill, minmax(210px, 1fr)) and check the computed track count at 320, 768 and 1280px with the script pattern from this lesson.
  3. Pick one row of cards that must line up, for example related products, and give them grid-row: span N with grid-template-rows: subgrid; measure that their footers share a y coordinate.

Decide deliberately between auto-fill and auto-fit for your catalogue, and write one sentence in your notes saying why.

09. Review prompt

Without looking back: what does each quoted string in grid-template-areas mean, and what happens when the rows disagree about cell counts? How does repeat(auto-fill, minmax(200px, 1fr)) decide the number of columns, and what does auto-fit do differently when items run out? What does subgrid share between parent and child, and how do subgrid gaps interact with the parent grid's gutters?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check