Thuta Learning
CSS
AdvancedWeb DevelopmentBeginner

Grid Container

CSSLesson 2130 min

What you'll walk away with

  • Calculate how fr shares the space left after gaps and fixed tracks
  • Explain how repeat(auto-fit, minmax(...)) picks a column count, and how auto-fit differs from auto-fill
  • Build a page shell with grid-template-areas and restack it into one column with a media query
  • Fix container-level bugs such as 1fr blowout and minmax() overflow

Explain it simply

Explain it simply

The previous lesson showed that a grid container draws its lines first. This lesson is about how far apart those lines go. grid-template-columns states the width of every column: a fixed value like 200px, a share of the leftover space like 1fr, or a rule like minmax(220px, 1fr), meaning "at least 220px, and an equal share of anything extra".

Combine that rule with repeat(auto-fit, ...) and you hand the browser a job: fit as many columns as there is room for. Wide screens get more columns, narrow screens get fewer, and you write no breakpoints at all.

Problem → Why → Solution

The problem: a staircase of media queries for column counts

Imagine a card list written with four media queries so it shows 1, 2, 3 or 4 columns depending on the screen. The breakpoints look at the viewport, so when the list moves into a narrower area beside a sidebar, it still shows four columns and the cards get squashed. Changing the minimum card width means recalculating all four breakpoints.

.cards { display: grid; gap: 20px; grid-template-columns: 1fr; }

@media (min-width: 520px)  { .cards { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 800px)  { .cards { grid-template-columns: repeat(3, 1fr); } }
@media (min-width: 1080px) { .cards { grid-template-columns: repeat(4, 1fr); } }
/* inside a 600px-wide panel on a 1200px screen: still 4 squashed columns */

Why do the breakpoints get it wrong?

A media query only asks about the viewport; it knows nothing about the width of the container the cards actually live in. What you really mean is a single rule: every card needs at least 220px, so fit as many as possible. repeat(auto-fit, minmax(220px, 1fr)) states that rule directly and is calculated from the container's own width.

Core concept: how the browser sizes tracks

Each space-separated value in grid-template-columns is one column track; grid-template-rows does the same for rows. A value can be a length such as px, rem or %, auto (sized by content), or fr. An fr is a fraction: the browser first subtracts fixed tracks and gaps, then divides only what is left in proportion to the fr values. In an 800px container, 200px 1fr 2fr with a 20px gap leaves 800 − 200 − 40 = 560px, so 1fr is 186.67px and 2fr is 373.33px.

repeat(4, 1fr) is shorthand for writing 1fr four times. minmax(min, max) clamps a track: never narrower than min, never wider than max. Combine them with auto-fit or auto-fill and the browser chooses the count: it fits as many tracks of the min width (plus gaps) as possible, then the 1fr maximum shares out the leftover. In a 1000px container, minmax(220px, 1fr) with a 20px gap fits four columns of 235px; five would need 1180px.

auto-fill and auto-fit only differ when there are few items. auto-fill keeps every track that fits, even empty ones, so two items stay track-sized on the left. auto-fit collapses the empty tracks to zero, so the two items stretch across the whole row. Once there are enough items to fill a row, the two behave identically. In the DevTools Computed tab, an auto-fit grid's grid-template-columns shows the collapsed tracks as 0px, for example "480px 480px 0px 0px".

Rows can be declared up front with grid-template-rows, but extra items still create implicit rows, and grid-auto-rows (for example minmax(120px, auto)) sizes those. gap, shorthand for row-gap and column-gap, sits only between tracks and is subtracted before any fr is calculated.

Mental model: how the width is shared out
  1. Take the container's width
  2. Subtract fixed tracks and gaps
  3. auto-fit: count how many min widths fit
  4. Share what is left by the fr ratios

fr always divides the leftover space, never the whole container.

General pattern

css
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-size, 1fr));
  grid-auto-rows: row-size;            /* rows the browser creates */
  gap: row-gap column-gap;
  grid-template-areas:
    "name name"
    "name name";                       /* one string per row */
}

Describe the columns as a rule (a min size and 1fr), size the browser-made rows with grid-auto-rows, and optionally name areas: each string is one row and each word is one cell.

Example: a responsive card grid without media queries

This example replaces the four breakpoints from the problem with a single line. Put six cards inside it and drag the browser window wider and narrower; with the DevTools grid overlay on, you can watch the column count change.

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

.card {
  padding: 20px;
  border-radius: 16px;
}

Code breakdown

  1. auto-fitgrid-template-columns: repeat(auto-fit, minmax(220px, 1fr));

    Instead of a fixed count, this says "as many 220px columns as fit with 20px gaps". A 984px container gets four, a 484px container two, and anything under 460px one.

  2. minmax(220px, 1fr)minmax(220px, 1fr)

    No column drops below 220px. Once the count is chosen, the 1fr maximum shares the spare space evenly, so no gap is left at the right end of the row.

  3. gap: 20px;gap: 20px;

    The gap counts when the browser works out how many columns fit: two columns need 220 + 20 + 220 = 460px.

  4. .card {.card {

    Notice the card has no width or margin. The container decides its size; the card only carries inner styling such as padding and border-radius.

You should see
A 984px container shows four 231px columns, a 484px one shows two 232px columns, and below 460px the cards stack in one column. No media query is involved.

Page shells with grid-template-areas

Instead of line numbers you can name areas. In grid-template-areas each string is a row and each word a cell; cells with the same name merge into one area, and . marks an empty cell. An item joins an area with grid-area: main. The best part: to change the layout on mobile, you leave the HTML alone and just rewrite the strings inside a media query.

.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-areas:
    "header header"
    "nav    main"
    "footer footer";
}

@media (max-width: 600px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas: "header" "nav" "main" "footer";
  }
}
ValueTwo items in a 980px container
repeat(auto-fill, minmax(200px, 1fr))Four 230px tracks remain; the items are 230px and two tracks sit empty
repeat(auto-fit, minmax(200px, 1fr))Empty tracks collapse to 0, so each item grows to 480px

In real projects

Where this shows up in real projects

Product listings, blog card lists and dashboard widgets lean heavily on repeat(auto-fit, minmax(...)). Component libraries often expose the minimum width as a custom property such as --card-min, so each page tunes the density by changing one value. Sections that may hold only a few items, like "Related articles", usually choose auto-fill, so a single article stays card-sized instead of stretching across the screen.

Admin panels and app shells describe header, sidebar, content and footer with grid-template-areas. The template strings read like a sketch of the layout, which makes code review easy. Moving the sidebar below the content on mobile is just an edit to the area strings, not the HTML, but remember that keyboard Tab order still follows the HTML source order.

Common mistakes

Common mistakes

1. A long URL blowing out a 1fr column

The minimum of 1fr is not zero but the content's min-content size (1fr means minmax(auto, 1fr)). With 1fr 1fr in a 400px container, one long unbreakable URL makes the first column far wider than 200px and pushes the grid out of its container. Write minmax(0, 1fr) and add overflow-wrap: anywhere on the item.

2. A container narrower than the minimum

With minmax(220px, 1fr) a column never drops below 220px, so inside a 180px-wide panel the card stays 220px and a horizontal scrollbar appears. Writing minmax(min(220px, 100%), 1fr) lets the minimum shrink to the container's width when space is tight.

3. Areas that are not rectangles

An L-shaped area such as "a b" "b b" makes the browser reject the entire grid-template-areas declaration, and the computed value is none. Every area must be a rectangle, and every string must have the same number of cells.

Best practices

Best practices

  • For card lists, try repeat(auto-fit, minmax(min(X, 100%), 1fr)) before writing a staircase of breakpoints.
  • Use minmax(0, 1fr) instead of 1fr for columns whose content can be long.
  • Give areas meaningful names like header, nav and main, and change layouts by rewriting only the strings in a media query.

Mini challenge

Mini challenge: a dashboard shell

Build a dashboard shell with header, menu, main and footer using grid-template-areas. Lay out the widgets inside main with an auto-fill grid, and switch the shell to one column below 600px.

  • .shell has two columns (220px and the rest), three rows (auto, 1fr, auto), a 16px gap and min-height: 100vh
  • Areas are head head / side main / foot foot, and each child joins its area with grid-area
  • .widgets uses repeat(auto-fill, ...) with a 160px minimum that cannot overflow a narrow container
  • Under max-width: 600px, restack the areas as head / side / main / foot
dashboard.html
<style>
  body { margin: 0; }
  /* TODO: .shell - columns, rows, named areas, gap, full viewport height */

  /* TODO: connect header, nav, main and footer to their areas */

  /* TODO: .widgets - auto-fill columns, at least 160px (but never overflow) */

  /* TODO: below 600px - one column, areas stacked top to bottom */
</style>
<div class="shell">
  <header>Header</header>
  <nav>Menu</nav>
  <main>
    <div class="widgets"><div>Sales</div><div>Users</div><div>Errors</div></div>
  </main>
  <footer>Footer</footer>
</div>

Expected: At a 1000px viewport, Header and Footer span 1000px, Menu is 220px, main is 764px and the footer sits at the bottom of the screen. The three widgets are 182px each with a fourth, empty track. At 500px everything is 500px wide and stacked, and the widgets form two 244px columns.

Show hint

Put one area string per line so the template reads like the layout. Use min(160px, 100%) as the minmax minimum to prevent overflow. On mobile, rewrite grid-template-rows for four rows as well, with main on the 1fr row.

Show solution
dashboard.html
<style>
  body { margin: 0; }
  .shell {
    display: grid;
    grid-template-columns: 220px 1fr;
    grid-template-rows: auto 1fr auto;
    grid-template-areas:
      "head head"
      "side main"
      "foot foot";
    gap: 16px;
    min-height: 100vh;
  }
  .shell > header { grid-area: head; }
  .shell > nav    { grid-area: side; }
  .shell > main   { grid-area: main; }
  .shell > footer { grid-area: foot; }
  .widgets {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(min(160px, 100%), 1fr));
    gap: 12px;
  }
  @media (max-width: 600px) {
    .shell {
      grid-template-columns: 1fr;
      grid-template-rows: auto auto 1fr auto;
      grid-template-areas: "head" "side" "main" "foot";
    }
  }
</style>
<div class="shell">
  <header>Header</header>
  <nav>Menu</nav>
  <main>
    <div class="widgets"><div>Sales</div><div>Users</div><div>Errors</div></div>
  </main>
  <footer>Footer</footer>
</div>

Quick quiz 1 / 3

In a 900px container with grid-template-columns: 300px 1fr 1fr and no gap, how wide is each 1fr column?

Quick quiz 2 / 3

A wide container holds only two items, and you want them to stretch across the whole row. Which value do you use?

Quick quiz 3 / 3

A 400px grid with grid-template-columns: 1fr 1fr overflows its container because of one long unbreakable string. What is the fix?

What to remember

  • fr divides the space left after fixed tracks and gaps, in proportion to the fr values.
  • repeat(auto-fit, minmax(min(X, 100%), 1fr)) picks a column count from the container's width, no breakpoints needed.
  • auto-fill keeps empty tracks while auto-fit collapses them; they only differ when items are few.
  • grid-template-areas describes a layout with named rectangular areas, and a media query can restack it by rewriting the strings.

Basic concepts of Grid layout — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Grid Container | Thuta Learning