CSS Grid: Two-Dimensional Layouts Without the Guesswork

Learn CSS Grid properly: tracks, fr units, minmax(), auto-fill vs auto-fit, named areas, line placement, the implicit grid, and the 1fr overflow fix.

Executive Summary: CSS Grid moves layout decisions from the children to the container. You define rows and columns once, then place items by line, by span or by named area, and the browser keeps everything aligned in both directions. The concepts that remove the guesswork are the fr unit and its hidden minimum, minmax() with auto-fill or auto-fit for responsive grids without media queries, named lines and areas for readable placement, and the implicit grid for content you did not plan for.
Three by three CSS grid with one item spanning two columns

Before Grid, page layouts were built from rows of wrappers: a .row containing .col-md-8 and .col-md-4, each containing more rows. Changing the layout meant changing the HTML. Aligning a card’s footer with the next card’s footer meant JavaScript that measured heights. The layout lived in the markup because CSS had no way to describe it.

CSS Grid Layout is a two-dimensional layout system. A grid container defines columns and rows, called tracks, and its children are placed into the cells and areas those tracks create. Unlike Flexbox, which sizes items along one axis from their content, Grid sizes tracks across both axes, so an item in row two lines up with an item in row one by definition. It has worked in every major browser since 2017. If you want a gentler first look, my older introduction to web design with CSS Grid covers the basics; this guide goes deeper.

My position: Grid is the default for anything with structure, and Flexbox is the exception for things that flow. Teams that reach for Flexbox first end up recreating Grid with percentages and negative margins.

The vocabulary you need

  • Grid lines are the dividing lines. A three-column grid has four column lines, numbered 1 to 4 from the start, and -1 to -4 from the end.
  • Tracks are the spaces between two adjacent lines: columns and rows.
  • Cells are the intersections of one row and one column.
  • Areas are rectangles of one or more cells, optionally named.
  • Gaps are the gutters between tracks, set with gap, row-gap and column-gap.
  • The explicit grid is the set of tracks you define. The implicit grid is the extra tracks the browser creates when items land outside it.

Defining tracks

grid-template-columns and grid-template-rows take a list of track sizes. Each size can be any of these:

Size Meaning
200px, 12rem, 30% A fixed or percentage size
1fr One share of the remaining free space
auto Sized to content, and stretches to fill if there is room
min-content As narrow as the content can go, usually its longest word
max-content As wide as the content wants with no wrapping
fit-content(20rem) Content size, but capped at 20rem
minmax(12rem, 1fr) Never smaller than 12rem, grow up to one share
repeat(3, 1fr) A shorthand for repeating a pattern
.layout {
  display: grid;
  grid-template-columns: 16rem 1fr;         /* fixed sidebar, flexible main */
  grid-template-rows: auto 1fr auto;        /* header, content, footer */
  gap: 1.5rem;
  min-height: 100dvh;
}

How the fr unit works

The browser first sizes every non-fr track and subtracts the gaps. Whatever is left is divided among the fr tracks in proportion to their numbers. In a 1000px container with grid-template-columns: 200px 1fr 2fr and a gap of 20px, the free space is 1000 – 200 – 40 = 760px, so the columns are 200px, about 253px and about 507px.

Unlike percentages, fr already accounts for gaps. Three columns of 33.33% plus two gaps overflow the container. Three columns of 1fr never do.

The hidden minimum in 1fr

Here is the Grid version of the Flexbox min-width: auto bug. A bare 1fr track is treated as minmax(auto, 1fr). Its minimum is the content’s minimum size, so a long URL, a wide table or a <pre> block makes the column refuse to shrink, and the page scrolls sideways.

/* WRONG: a code block in the main column forces horizontal page scroll */
.layout { grid-template-columns: 16rem 1fr; }

/* RIGHT: allow the column to shrink below its content */
.layout { grid-template-columns: 16rem minmax(0, 1fr); }
pre { overflow-x: auto; }   /* the code block scrolls, not the page */

Use minmax(0, 1fr) for any column that might hold unbreakable content. Setting min-width: 0 on the grid item works too, for the same reason it does in Flexbox, covered in the Flexbox mental model guide.

Responsive grids without media queries

The most-used line of Grid CSS builds a card grid that adds and removes columns on its own:

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

Read it inside out. Each column is at least 16rem and at most one share of the space. auto-fill creates as many columns as fit. The min(16rem, 100%) guard stops a single column from overflowing on screens narrower than 16rem, where a plain 16rem minimum would force horizontal scrolling. Unlike wrapping Flexbox, the last row’s cards keep the same width as every other row, because they sit in the same column tracks.

auto-fill vs auto-fit

The two keywords differ only when there are fewer items than columns that would fit.

Keyword Empty tracks Effect with 2 items in a 1200px container Use for
auto-fill Kept at their size Items stay card-width; empty columns hold the rest Card grids, galleries: consistent item width
auto-fit Collapsed to zero Two items stretch to fill the whole row Feature rows, button groups: fill the line

For product grids I nearly always want auto-fill. A search that returns two results should not show two cards each half a screen wide.

Placing items

By default, items fill the grid in source order, one per cell. You can place any item explicitly with line numbers, spans or names.

.hero    { grid-column: 1 / -1; }          /* from the first line to the last: full width */
.feature { grid-column: span 2; }          /* two columns wide, wherever it lands */
.sidebar { grid-column: 3; grid-row: 1 / span 3; }
.footer  { grid-row: -2 / -1; }            /* the last explicit row */

Negative line numbers count from the end of the explicit grid. 1 / -1 is the cleanest way to say “full width” and keeps working when someone changes the column count.

Named areas

grid-template-areas lets you draw the layout as text. Each string is a row, each word is a cell, and a dot marks an empty cell. Every named area must form a rectangle.

.page {
  display: grid;
  grid-template-columns: 16rem minmax(0, 1fr);
  grid-template-areas:
    "header  header"
    "nav     main"
    "footer  footer";
  gap: 1rem;
}

.page > header { grid-area: header; }
.page > nav    { grid-area: nav; }
.page > main   { grid-area: main; }
.page > footer { grid-area: footer; }

@media (width < 48rem) {
  .page {
    grid-template-columns: minmax(0, 1fr);
    grid-template-areas:
      "header"
      "main"
      "nav"
      "footer";
  }
}

The responsive version only changes the template. No item rules change, and no markup changes. That is the core benefit of Grid: the layout is one readable picture in one place.

Named lines and the full-bleed layout

You can name lines in square brackets. Lines named foo-start and foo-end automatically create an area called foo. This enables my favorite article layout, where text stays at a readable width but images and callouts can break out to the edges:

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

.content-grid > * { grid-column: content; }
.content-grid > .full-bleed { grid-column: full; }

Every child sits in the readable center column. Anything with .full-bleed spans edge to edge. No negative margins, no 100vw hacks that cause horizontal scrollbars when a vertical scrollbar is present.

The implicit grid and auto-placement

If you define three columns and add ten items, the browser creates extra rows to hold them. Those are implicit tracks, sized by grid-auto-rows (or grid-auto-columns), which default to auto.

.gallery {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: minmax(10rem, auto);   /* every new row at least 10rem */
  grid-auto-flow: dense;                 /* fill holes left by spanning items */
}

.gallery .wide { grid-column: span 2; }
.gallery .tall { grid-row: span 2; }

grid-auto-flow: dense back-fills gaps with later items that fit. It produces a tidy mosaic, but it also means visual order no longer matches source order. Use it for galleries of independent images, not for content where reading order or keyboard focus order matters.

A true masonry layout, where items of different heights pack tightly into columns, is still emerging. Browsers are working on a native answer, but until it is cross-browser, use CSS columns or a fixed-row mosaic as the fallback.

Alignment

Grid has two levels of alignment, and the property names tell you which one you are setting.

  • justify-items and align-items position every item inside its own cell, on the inline and block axes. The default is stretch.
  • justify-self and align-self do the same for one item.
  • justify-content and align-content position the whole set of tracks inside the container, which only matters when the tracks are smaller than the container.
  • place-items, place-self and place-content are shorthands for the block and inline pairs.

The shortest centering code in CSS is Grid: display: grid; place-items: center;.

Overlapping items on purpose

Grid items can occupy the same cells. That replaces most uses of absolute positioning for overlays, and it keeps both elements in flow so the container still sizes to the taller one.

.hero {
  display: grid;
}

.hero > * {
  grid-area: 1 / 1;       /* every child in the same cell */
}

.hero__image { z-index: 0; }
.hero__text  { z-index: 1; align-self: end; padding: 2rem; }

Grid items accept z-index without needing position, so stacking order is easy to control. If the text grows taller than the image, the hero grows with it, which an absolutely positioned overlay cannot do.

Inspect grids, do not guess

Firefox, Chrome, Edge and Safari all have a grid inspector in DevTools. Click the “grid” badge next to a container in the Elements panel to overlay line numbers, track sizes, area names and gaps on the page. When placement is off by one, the overlay shows which line you actually targeted in seconds.

Frequently Asked Questions

What is the difference between auto-fill and auto-fit in CSS Grid?

Both create as many tracks as fit in the container. auto-fill keeps any empty tracks at their size, so items keep a consistent width. auto-fit collapses empty tracks to zero, so the existing items stretch to fill the row. The difference only shows when there are fewer items than available columns.

Why does my 1fr column overflow the grid?

A 1fr track behaves like minmax(auto, 1fr), so its minimum is the content’s minimum width. Long URLs, tables or code blocks hold it open. Use minmax(0, 1fr) for the track, or min-width: 0 on the item, and let the wide content scroll inside itself.

Is CSS Grid better than Flexbox?

Neither is better in general. Grid suits layouts where items must align in rows and columns and the design defines the tracks. Flexbox suits single rows or columns where content should decide item sizes, such as navbars and button groups. Most pages use both.

Can I make a responsive grid without media queries?

Yes. grid-template-columns: repeat(auto-fill, minmax(min(16rem, 100%), 1fr)) adds and removes columns automatically based on the container width, with each column at least 16rem wide unless the container itself is narrower.

Let the container own the layout

Grid turns layout into a declaration on one element instead of a structure spread across wrappers. Define the tracks, name what matters, guard your fr minimums, and let auto-placement handle the rest. When components inside the grid need to align with it, the next step is subgrid and micro-grids.

Rule of thumb: if you are adding a wrapper div only to make a layout work, Grid can probably do it on the parent.

Originally posted on 19 June 2025 and post last modified on 19 June 2025

CSS CSS Grid CSS Layout Front-End Development

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *