Chapter 22 of 33

Grid Layout Patterns

In the CSS Grid chapter we learned the vocabulary: tracks, lines, fr, repeat(), minmax(), named areas and the implicit grid. Knowing the properties is one thing; knowing which combination solves a real layout problem is another.

This chapter is a collection of Grid recipes that you will meet in almost every project: a card gallery that adapts to any screen without media queries, the classic "holy grail" page, a footer that sticks to the bottom, a 12-column system, a magazine-style gallery, text on top of an image, a full-bleed article, and cards whose sections line up thanks to subgrid. For each pattern we look at the code, the result, and why it works.


Pattern 1: The Responsive Card Grid (No Media Queries)

This is the most famous Grid one-liner:

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

Read it as: "make as many columns as fit, each at least 200px wide, and then share any leftover space equally between them." On a wide screen you get four or five columns, on a phone you get one, and you didn't write a single breakpoint.

How the browser counts the columns

Take a 900px-wide container. The browser looks for the largest number of columns n such that n minimum-width columns plus the gaps between them still fit:

n = 4 → 4 × 200 + 3 × 10 = 830px  ≤ 900  ✔ fits
n = 5 → 5 × 200 + 4 × 10 = 1040px > 900  ✘ too wide
So: 4 columns.

Each column then stretches (the 1fr maximum):
(900 − 3 × 10) ÷ 4 = 870 ÷ 4 = 217.5px per column

Chrome reports exactly 217.5px 217.5px 217.5px 217.5px.

auto-fill vs auto-fit

The two keywords behave identically when there are enough items to fill a row. The difference shows up when there are fewer items than columns. With only two cards in the same 900px container:

auto-fill: keeps the 4 tracks, 2 of them empty
┌─────────┐ ┌─────────┐ ┌ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ┐
│ Card 1  │ │ Card 2  │   (empty)     (empty)
└─────────┘ └─────────┘ └ ─ ─ ─ ─ ┘ └ ─ ─ ─ ─ ┘
  217.5px     217.5px

auto-fit: collapses the empty tracks to 0, cards grow to fill the row
┌──────────────────────┐ ┌──────────────────────┐
│ Card 1               │ │ Card 2               │
└──────────────────────┘ └──────────────────────┘
          445px                    445px

Measured in Chrome: auto-fill gives two 217.5px cards, while auto-fit gives two 445px cards (the empty tracks become 0px).

auto-fillauto-fit
Creates as many tracks as fitYesYes
Empty tracksKept (take up space)Collapsed to 0
With few itemsItems keep a "normal" widthItems stretch across the row
Good forProduct grids where a lone item shouldn't become hugeSmall sets (e.g. 2-3 feature boxes) that should fill the width

Making it safe on very small screens

If the container is narrower than 200px (a tiny phone, or a narrow sidebar), minmax(200px, 1fr) still insists on 200px and the grid overflows horizontally. The fix is to use min() so the minimum never exceeds the container:

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr));
  gap: 16px;
}

min(100%, 220px) picks whichever is smaller: in a 900px container it is 220px; in a 180px container it becomes 180px (100%), so one column fits perfectly. (min(), max() and clamp() are covered fully in Modern CSS: :has(), Nesting, clamp() & Logical Properties.)

Worked example: a container 900px wide with padding: 16px has a content box of 900 − 32 = 868px. Four columns would need 4 × 220 + 3 × 16 = 928px, which doesn't fit, so five cards come out as three columns of (868 − 32) ÷ 3 ≈ 278.7px each, with cards 4 and 5 on the second row. Shrink the window and it becomes two columns, then one.


Pattern 2: The Holy Grail Layout

The "holy grail" is the classic website skeleton: header, footer, a main column and two sidebars. Before Grid it needed floats and tricks; with named areas it reads like a sketch.

<div class="page">
  <header class="header">Header</header>
  <nav class="nav">Navigation</nav>
  <main class="main">Main content</main>
  <aside class="ads">Related</aside>
  <footer class="footer">Footer</footer>
</div>
.page {
  display: grid;
  min-height: 100vh;
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header header"
    "nav    main   ads"
    "footer footer footer";
  gap: 1rem;
}

.header { grid-area: header; }
.nav    { grid-area: nav; }
.main   { grid-area: main; }
.ads    { grid-area: ads; }
.footer { grid-area: footer; }
┌──────────────────────────────────────────────┐
│ Header                                       │  auto (content height)
├──────────┬────────────────────────┬──────────┤
│ Nav      │ Main content           │ Related  │  1fr (all remaining height)
│ 200px    │ 1fr                    │ 200px    │
├──────────┴────────────────────────┴──────────┤
│ Footer                                       │  auto
└──────────────────────────────────────────────┘

Why these values?

  • grid-template-rows: auto 1fr auto: header and footer are as tall as their content; the middle row takes all remaining height.

  • min-height: 100vh: the page is at least one screen tall, so there is "remaining height" for the middle row to absorb, and the footer sits at the bottom even on short pages.

  • The three columns stay equally tall automatically, because they share a row.

On a phone, three columns are too many. Because the structure lives in grid-template-areas, a narrow version only needs different strings, for example "header" "nav" "main" "ads" "footer" with grid-template-columns: 1fr. In Responsive Design & Media Queries we wrap exactly that change in a media query.


Problem: on a page with little content, the footer floats up into the middle of the screen. We want it at the bottom of the window when content is short, and after the content when it is long.

body {
  margin: 0;
}

.page {
  display: grid;
  min-height: 100vh;
  grid-template-rows: auto 1fr auto;   /* header, main, footer */
}
<div class="page">
  <header>Header</header>
  <main>Only one line of content</main>
  <footer>Footer</footer>
</div>

The 1fr row soaks up all spare height, pushing the footer down. If the content is long, the grid simply grows past 100vh and the footer follows the content. Rendered in a 900px-tall window with almost no content, the header sits at the top and the footer touches the bottom edge.

On mobile browsers, 100vh can be taller than the visible area when the address bar is showing. If that matters, use min-height: 100dvh (dynamic viewport height), which we met in CSS Units.


Pattern 4: Sidebar + Content

The simplest two-column layout:

.with-sidebar {
  display: grid;
  grid-template-columns: minmax(180px, 250px) minmax(0, 1fr);
  gap: 2rem;
}
  • The sidebar flexes between 180px and 250px.

  • The content column takes the rest. minmax(0, 1fr) (instead of plain 1fr) stops a wide code block or table from pushing the layout wider than the screen, the "1fr is not always equal" problem from the CSS Grid chapter.


Pattern 5: A 12-Column Layout System

Design tools and frameworks like Bootstrap think in 12 columns, because 12 divides evenly into halves, thirds, quarters and sixths. In plain Grid this is a few lines:

.row {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 1rem;
}

.col-12 { grid-column: span 12; }   /* full width   */
.col-6  { grid-column: span 6; }    /* half         */
.col-4  { grid-column: span 4; }    /* one third    */
.col-3  { grid-column: span 3; }    /* one quarter  */
.col-8  { grid-column: span 8; }    /* two thirds   */
<div class="row">
  <div class="col-8">Article</div>
  <div class="col-4">Sidebar</div>
  <div class="col-4">A</div>
  <div class="col-4">B</div>
  <div class="col-4">C</div>
</div>
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │10 │11 │12 │
├───────────────────────────────┬───────────────┤
│ Article (span 8)              │ Sidebar (4)   │
├───────────────┬───────────────┼───────────────┤
│ A (span 4)    │ B (span 4)    │ C (span 4)    │
└───────────────┴───────────────┴───────────────┘

Unlike old float-based grid systems, there is no "row" wrapper per line and no clearing: when a row's 12 columns are used up, auto-placement simply moves to the next row.


Galleries look more interesting when some images are bigger. Combine span with grid-auto-flow: dense:

.gallery {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: 60px;
  gap: 8px;
  grid-auto-flow: dense;
}

.gallery .big { grid-column: span 2; grid-row: span 2; }
<div class="gallery">
  <div>1</div>
  <div class="big">2 big</div>
  <div>3</div>
  <div class="big">4 big</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>

Here is what Chrome produces with and without the last line (grid-auto-flow: dense):

Without dense (default "row")          With dense
┌────┬─────────┬────┐                  ┌────┬─────────┬────┐
│ 1  │         │ 3  │  row 1           │ 1  │         │ 3  │
├────┤  2 big  ├────┤                  ├────┤  2 big  ├────┤
│    │         │    │  row 2 (2 holes) │ 5  │         │ 6  │
├────┴────┬────┼────┤                  ├────┴────┬────┼────┤
│         │ 5  │ 6  │  row 3           │         │ 7  │ 8  │
│  4 big  ├────┼────┤                  │  4 big  ├────┼────┤
│         │ 7  │ 8  │  row 4           │         │ 9  │ 10 │
├────┬────┼────┴────┘                  └─────────┴────┴────┘
│ 9  │ 10 │            row 5
└────┴────┘

Why the holes? Big item 4 needs a 2×2 space. It doesn't fit in row 1 (only column 4 is free) or rows 2-3 (item 2 is in the way), so it drops to rows 3-4. Without dense, auto-placement never goes back, so the two single cells left in row 2 stay empty and the grid needs five rows. With dense, the browser searches from the start of the grid for every item, so the small items 5 and 6 fill those holes and everything packs into four full rows. Remember the cost from the previous chapter: with dense the visual order can differ from the HTML order, so use it for pictures, not for text that must be read in sequence.

What about real masonry (Pinterest style)?

The gallery above still uses fixed rows. A true masonry layout, where items of different heights pack tightly into columns, is being standardised as display: grid-lanes. As of late 2026 it ships in Safari (from 26.4) but not yet in stable Chrome or Firefox, so it is not Baseline. If you try it, put it inside @supports (display: grid-lanes) with a normal grid as the fallback.


Pattern 7: Overlapping Items (Text over an Image)

Grid allows two items to occupy the same cell. That gives a clean way to put a caption on top of an image without position: absolute:

<div class="hero">
  <img src="campus.jpg" alt="Students on campus">
  <h2>Learn CSS Grid</h2>
</div>
.hero {
  display: grid;
}

.hero > * {
  grid-area: 1 / 1;     /* every child goes into row 1, column 1 */
}

.hero img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hero h2 {
  place-self: end start;   /* bottom-left corner of the cell */
  margin: 1rem;
  color: white;
}

Both children sit in the single cell; the heading is painted on top because it comes later in the HTML (use z-index, from z-index & Stacking Context, to change that). Compared to absolute positioning:

Grid stackingposition: absolute
Container heightGrows to fit the taller child (image or text)Absolutely positioned text is ignored; long text can spill out
Alignmentplace-self, easy to centre or pin to a cornertop/left/transform arithmetic
Needs position: relative parentNoYes

Pattern 8: Full-Bleed Article Layout with Named Lines

Blog posts usually keep text in a narrow, readable column (around 60-70 characters per line), but want some images or code blocks to stretch edge to edge. Named grid lines handle this elegantly:

.article {
  display: grid;
  grid-template-columns:
    [full-start] 1fr
    [content-start] min(65ch, 100% - 2rem) [content-end]
    1fr [full-end];
}

.article > * {
  grid-column: content;       /* normal elements: middle column */
}

.article > .full-bleed {
  grid-column: full;          /* edge to edge */
}

How it works:

  • Names in square brackets label the lines. A pair named content-start and content-end creates an implicit area called content, so grid-column: content means "from content-start to content-end". The same goes for full.

  • The middle column is 65ch wide on big screens; on small screens it becomes the full width minus 2rem, which leaves 1rem of space on each side.

  • The two 1fr columns share whatever is left, centring the text column.

│← 1fr →│←──── content (≤ 65ch) ────→│← 1fr →│
│       │ Paragraph text …            │       │
│       │ Paragraph text …            │       │
│███████████ full-bleed image ███████████████│
│       │ Paragraph text …            │       │

Tested in Chrome in an 800px container with a 14px Arial font: the paragraph column measured about 506px wide (65ch at that font), with about 147px on each side, while the full-bleed element spanned the full 800px.


Pattern 9: Aligned Cards with subgrid

Here is a problem everyone hits. Three cards sit side by side, each with a title, a description and a button. The titles have different lengths, so the descriptions and buttons don't line up across cards:

Without subgrid                       With subgrid
┌────────┐┌────────┐┌────────┐        ┌────────┐┌────────┐┌────────┐
│Short   ││A much  ││Mid     │        │Short   ││A much  ││Mid     │
│text…   ││longer  ││text…   │        │        ││longer  ││        │
│[Buy]   ││title   ││[Buy]   │        │        ││title   ││        │
│        ││text…   ││        │        │text…   ││text…   ││text…   │
│        ││[Buy]   ││        │        │[Buy]   ││[Buy]   ││[Buy]   │
└────────┘└────────┘└────────┘        └────────┘└────────┘└────────┘

Each card is its own little layout, so it can't know how tall the other cards' titles are. subgrid solves this: a nested grid can use its parent's tracks instead of creating its own.

<div class="cards">
  <article class="card">
    <h3>Short</h3>
    <p>Description…</p>
    <a href="#">Buy</a>
  </article>
  <!-- two more cards -->
</div>
.cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.card {
  display: grid;
  grid-row: span 3;                 /* each card covers 3 rows of the parent */
  grid-template-rows: subgrid;      /* ...and uses those rows for its children */
  gap: 8px;                         /* optional: override the inherited row gap */
}

Now the parent grid has three shared rows: a title row, a description row and a button row. Each row is as tall as the tallest content placed in it from any card. In our Chrome test, the button in every card started at exactly the same y-coordinate, even though only one card had a three-line title.

Key facts about subgrid:

  • It works for rows, columns, or both (grid-template-columns: subgrid).

  • The subgrid must span the parent tracks it wants to use (here grid-row: span 3).

  • It inherits the parent's gap by default; you may override it.

  • Support: Firefox had it first (2019); Chrome and Edge added it in version 117 (2023). It became Baseline in September 2023 and is now Baseline: widely available.


Pattern 10: Centring Anything

From the CSS Grid chapter, the shortest centring code in CSS:

.center {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

Useful for login screens, loading spinners and "404" pages.


Choosing the Right Pattern

NeedPatternKey code
Cards that adapt to any widthResponsive card gridrepeat(auto-fit, minmax(min(100%, 220px), 1fr))
Whole-page skeletonHoly grailgrid-template-areas + auto 1fr auto rows
Footer at the bottom of short pagesSticky footermin-height: 100vh; grid-template-rows: auto 1fr auto
Bootstrap-like columns12-column systemrepeat(12, minmax(0, 1fr)) + span n
Mixed-size pictures without holesMagazine galleryspan + grid-auto-flow: dense
Text on an imageOverlapgrid-area: 1 / 1 on all children
Readable article with wide imagesFull-bleednamed lines [content-start]…
Card sections aligned across cardsSubgridgrid-template-rows: subgrid

Common Mistakes

  • Forgetting min() in the card grid. minmax(250px, 1fr) overflows containers narrower than 250px.

  • Using auto-fill when you wanted items to stretch (or the reverse). Test with only one or two items to see the difference.

  • Sticky footer without min-height. The 1fr row has no spare height to absorb, so the footer doesn't move.

  • Subgrid without spanning. If the card doesn't span 3 parent rows, there are no tracks for its 3 children to use.

  • Using dense on reading content. It changes the visual order and confuses keyboard and screen-reader users.

  • Plain 1fr next to wide content. Code blocks and tables blow the column out; use minmax(0, 1fr).


Interview & Exam Questions

1. A container is 1000px wide. With repeat(auto-fill, minmax(220px, 1fr)) and gap: 20px, how many columns are created and how wide is each?

Try n = 4: 4 × 220 + 3 × 20 = 940 ≤ 1000 ✔. n = 5: 5 × 220 + 4 × 20 = 1180 > 1000 ✘. So 4 columns, each (1000 − 60) ÷ 4 = 235px.

2. What is the difference between auto-fill and auto-fit?

Both create as many tracks as fit. auto-fill keeps empty tracks, so with few items the items stay at their "normal" size and empty space remains. auto-fit collapses empty tracks to zero, so the existing items stretch to fill the row. With enough items to fill the row, they behave the same.

3. How do you put a footer at the bottom of the viewport on short pages using Grid?

Make the page wrapper a grid with min-height: 100vh (or 100dvh) and grid-template-rows: auto 1fr auto. The 1fr main row absorbs spare height and pushes the footer down.

4. What problem does subgrid solve?

Nested grids normally size their own tracks independently, so content inside sibling components (like titles and buttons in cards) can't align. With grid-template-rows: subgrid (or columns), the nested grid uses the parent's tracks, so the same row in every card has the same height and everything lines up.

5. How can you overlay text on an image with Grid instead of absolute positioning, and what is the advantage?

Put both elements in the same cell with grid-area: 1 / 1, then align the text with place-self. The container's height accounts for both children, so long text can't spill out, and no position or offsets are needed.


Summary

  • repeat(auto-fit | auto-fill, minmax(min(100%, X), 1fr)) is a responsive grid with no media queries; auto-fit stretches items, auto-fill keeps empty tracks.

  • Named areas make page skeletons (holy grail) readable and easy to rearrange.

  • auto 1fr auto rows with min-height: 100vh give a sticky footer.

  • repeat(12, minmax(0, 1fr)) plus span replaces framework grid systems.

  • span + dense builds packed galleries; true masonry (grid-lanes) is not yet Baseline.

  • Items can share a cell (grid-area: 1 / 1) for overlays; named lines create full-bleed layouts.

  • subgrid (widely available) aligns the insides of sibling components.

Several of these patterns adapt by themselves, but sometimes a layout needs to change at specific screen sizes. That is the job of the next chapter, Responsive Design & Media Queries.