-- online Search!

CSS Grid Fundamentals

by kirupa   |   filed under HTML and CSS

TL;DR

Setting display: grid on a container divides it into rows and columns. grid-template-columns sizes the columns, with the fr unit sharing the leftover space, and items go wherever we place them by line number or named area. repeat(auto-fill, minmax()) fits as many columns as possible, and subgrid lets cards share their parent's rows.

  • In an 800px grid with columns of 200px 1fr 2fr, the fixed column is sized first, and the 600px left over splits into 200px and 400px.
  • Grid lines are numbered from 1, and -1 always means the last line, so grid-column: 3 / -1 runs to the end no matter how many columns there are.
  • grid-template-areas draws the layout as strings of area names, and a media query can redraw it for small screens without touching the HTML.
  • With grid-row: span 3 and grid-template-rows: subgrid, every card in a row shares the same title, text, and button rows, so the buttons line up.

Some layouts are a single row or a single column, and Flexbox handles those beautifully. Many layouts aren't. A page has a header across the top, a sidebar next to the main content, and a footer at the bottom. A photo gallery has cards that need to line up in neat columns and neat rows. For those, we need a way to think in two directions at the same time.

In this article, we'll learn how to carve a container into rows and columns, size them, drop items exactly where we want them, give parts of our layout names, and build a gallery that fits any screen without a single media query. We'll finish with subgrid, which fixes a card alignment problem that used to be surprisingly annoying.

Onwards!

What Is CSS Grid?

Imagine drawing a few vertical lines and a few horizontal lines across a container, like the lines on a sheet of graph paper. Those lines divide the container into rows and columns, and each child of the container drops into one of the boxes between the lines. The container decides where the lines go, and the children just fill in the boxes. That's the idea behind CSS Grid Layout, or CSS Grid for short.

We turn it on with display: grid, and then we describe the columns we want:

.container {
  display: grid;
  grid-template-columns: 200px 200px 200px;
  gap: 10px;
}

This gives us three columns that are each 200px wide, with 10px of space between them. Every child of .container becomes a grid item and fills the next open spot, one row at a time. If you want to watch a grid like this come together from scratch, our Creating a 3x3 Grid tutorial builds one step by step. Here, we'll go one level deeper and look at all of the pieces that make a grid tick.

What Are Grid Lines, Tracks, and Cells?

A grid has a small vocabulary, and it's worth learning because the rest of CSS Grid is described with it. Here's a grid with three columns and two rows:

A grid with three columns and two rows. Numbered lines run along the top (1 to 4) and down the left side (1 to 3). The whole first row is highlighted as one track, and the cell in the second row and third column is highlighted as a single cell.

The lines that divide the grid are called grid lines, and the browser numbers them for us, starting at 1. Three columns have four column lines, and two rows have three row lines. The space between two neighboring lines is called a track, which is the general name for a row or a column. The highlighted first row is one track. A single box where a row and a column cross is a cell, like the highlighted one in the second row and third column. A rectangle made of several cells is called a grid area.

How Do We Size Columns and Rows?

The grid-template-columns and grid-template-rows properties take a list of sizes, one per track. We can use any CSS length, like pixels or percentages, and the auto keyword, which makes a track as big as its content. Grid also brings a unit of its own, the fr unit, which stands for a fraction of the space that's left over. Here's an 800px grid with one fixed column and two flexible ones:

An 800px grid with columns set to 200px 1fr 2fr. The 200px column gets its size first, which leaves 600px. That leftover space is split into three equal shares of 200px, so the 1fr column is 200px wide and the 2fr column is 400px wide.

The browser sizes the 200px column first, because it's fixed. That leaves 600px for the two fr columns. Together they ask for three fractions (1 plus 2), so each fraction is worth 200px. The 1fr column gets one of them and ends up 200px wide, and the 2fr column gets two of them and ends up 400px wide. If the grid gets wider or narrower, the fixed column stays at 200px, and only the fr columns change.

Typing the same size over and over gets old quickly, so there's a repeat() function. There's also minmax(), which gives a track a smallest and a largest size:

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: minmax(100px, auto);
  gap: 10px 20px;
}

Here, repeat(3, 1fr) is the same as writing 1fr 1fr 1fr, and it gives us three equal columns. The minmax(100px, auto) row is at least 100px tall and grows taller when its content needs more room. The gap property takes two values when we want different spacing between rows (10px) and between columns (20px).

How Do We Place Items on the Grid?

When we don't say anything, items fill the grid one cell at a time, in the order they appear in our HTML. That's called auto-placement, and it's often all we need. When we want an item somewhere specific, or want it to cover more than one cell, we use the line numbers we saw earlier. Here's a grid with four columns and three rows, and three items placed on it:

A grid with four columns and three rows. Item A spans from column line 1 to 3 in the first row. Item B spans from column line 3 to -1, the last line, and from row line 1 to 3, so it covers two columns and two rows. Item C uses span 2 and lands in the first open spot, the second row's first two columns.

Item A starts at column line 1 and ends at column line 3, so it covers the first two columns. Item B starts at column line 3 and ends at line -1. Negative numbers count backward from the end, so -1 is always the last line, no matter how many columns there are. It also covers row lines 1 to 3, which makes it two rows tall. Item C doesn't say where to start. It only says it wants to span two columns, so auto-placement drops it into the first open spot that's two columns wide, which is the start of the second row. Here's the CSS:

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

.a {
  grid-column: 1 / 3;
}

.b {
  grid-column: 3 / -1;
  grid-row: 1 / 3;
}

.c {
  grid-column: span 2;
}

When there are more items than cells, the grid adds new rows to hold them. These extra rows are called implicit rows, and they're only as tall as their content unless we size them with grid-auto-rows. Just like Flexbox's order, placing items by line number only changes where they show up. Keyboard and screen reader users still move through them in the order of our HTML, so it's best when the two orders agree.

How Do Named Grid Areas Work?

Line numbers work, but they're hard to read a week later. For a page layout, it's often nicer to draw the layout right in our CSS. The grid-template-areas property lets us do exactly that, one string of names per row:

On the left, the grid-template-areas value: header header, sidebar main, footer footer. On the right, the layout it creates: a header across the top, a sidebar and a main area side by side in the middle, and a footer across the bottom.

Every name in those strings is the name of an area. When a name repeats across a row, like header header, that area stretches across both columns. Then we tell each element which area it belongs in by giving it a matching grid-area name:

.page {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
  gap: 10px;
}

header { grid-area: header; }
aside  { grid-area: sidebar; }
main   { grid-area: main; }
footer { grid-area: footer; }

A period in the strings marks a cell we want to leave empty, and every area has to be a rectangle, so an L-shaped area won't work. The best part of named areas shows up on small screens. Inside a media query, we can redefine grid-template-areas as a single column, and the whole page rearranges itself without touching the HTML. Our Responsive Design and Media Queries tutorial shows how to pick when that happens.

How Do We Make a Grid That Fits Any Width?

For a gallery of cards, we usually don't care about the exact number of columns. We care that each card is at least a certain width, and we want as many columns as fit. Grid can figure that out on its own when we combine repeat() with the auto-fill or auto-fit keywords:

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

This line reads like a sentence: make as many columns as fit, where each one is at least 150px wide and they share any leftover space equally. When the gallery gets wider, more columns appear, and when it gets narrower, they wrap onto new rows. The two keywords only behave differently when there are fewer items than columns. Here's what happens with only three items in a 700px gallery, with no gap to keep the math simple:

Two 700px grids with columns set to repeat(auto-fill or auto-fit, minmax(150px, 1fr)) and only 3 items. 4 tracks fit. With auto-fill, the items take 3 of the 4 tracks, 175px each, and an empty track stays at the end. With auto-fit, the empty track collapses, so the 3 items stretch to 233px each.

Four 150px columns fit in 700px, so both grids start out with four columns that are 175px each. With auto-fill, the fourth column stays around even though nothing is in it, so our three items are 175px each and an empty track sits at the end. With auto-fit, the empty column collapses to nothing, and the three items stretch to share the whole width, which makes them about 233px each. Use auto-fill when items should keep a consistent size, and auto-fit when they should fill the row.

How Do We Line Things Up Inside a Grid?

Grid shares its alignment properties with Flexbox, and they work on two levels. The first level is the item inside its own cell. justify-items moves items along the row direction, align-items moves them along the column direction, and place-items sets both at once. Out of the box, they behave like stretch, which is why grid items normally fill their whole cell:

.container {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  place-items: center;
  justify-content: center;
}

The second level is the whole set of tracks inside the container. When our tracks add up to less than the container's size, like the three 100px columns above in a wider container, justify-content and align-content decide where the tracks go. A single item can also opt out of the group with justify-self and align-self.

What Is Subgrid?

Here's a problem that drove people up the wall for years. We have a row of cards, and each card has a title, some text, and a button. The titles have different lengths. The cards are grid items, so they line up with each other just fine, but the insides of the cards don't:

Two rows of three cards. Each card has a title, some body text, and a button, and the titles are one, two, and three lines long. Without subgrid, each card lays out on its own, so the body text and buttons start at different heights. With subgrid, the cards share the parent grid's rows, so every body and every button lines up across the cards.

Look at the cards on the left. Each card lays out its own title, text, and button without knowing anything about its neighbors. The card with the three-line title pushes its text and button further down than the others, and the whole row looks a bit messy. What we want is for the title, text, and button rows to be shared by every card in the row, so the tallest title decides where all of the text starts. That's what the cards on the right do.

To get there, each card needs to borrow its rows from the grid it lives in instead of making its own. A grid item that borrows its parent's tracks like this is called a subgrid. Here's the CSS:

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

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

Each card spans three rows of the gallery, one each for the title, the text, and the button. Setting grid-template-rows to subgrid tells the card to use those three gallery rows as its own rows. Because every card in a row shares the same gallery rows, the title row is as tall as the tallest title, and everything below it lines up. We can do the same thing with columns using grid-template-columns: subgrid.

Subgrid has worked in every major browser since September 2023. Firefox was first in version 71, Safari followed in version 16, and Chrome and Edge caught up in version 117.

Let's Play With a Grid

Here's a little gallery of breakfast cards that uses everything from the last few sections. You can switch between auto-fill and auto-fit, change the minimum card width and the number of cards, and turn subgrid on and off:

With subgrid turned off, notice how the Order buttons sit at different heights because of the long titles. Turning subgrid on lines them up, and the shorter titles simply get a little extra space below them.

When Should We Use Grid Instead of Flexbox?

A good rule of thumb is to think about where the sizes come from. With Flexbox, the content decides how big each item is, and the items flow along one line. With Grid, the container decides where the rows and columns go, and the content fills them in. So when things need to line up both across and down, like a page layout, a gallery, or a form with labels and fields, Grid is usually the better choice. When we have a row or a column of things that should size themselves, like a navigation bar or a group of buttons, Flexbox usually wins.

Most real pages use both. A grid lays out the page, and inside each grid area, a flex container lines up the little things. This very page works that way, with a grid that holds the article column and the sidebar next to it.

Frequently Asked Questions

What Does the fr Unit Mean in CSS Grid?

fr stands for fraction, and it’s a share of the space left over after the fixed-size tracks are sized. In an 800px grid with columns of 200px 1fr 2fr, the 200px column goes first, and the remaining 600px splits into one share of 200px and two shares of 400px.

What Is the Difference Between auto-fill and auto-fit?

Both make as many columns as fit, and they only behave differently when there are fewer items than columns. auto-fill keeps the empty columns, so the items stay the same size. auto-fit collapses the empty columns, so the items stretch to fill the row.

What Does a Negative Grid Line Number Mean?

Negative line numbers count backward from the end of the grid, so -1 is always the last line, no matter how many columns there are. That’s why grid-column: 3 / -1 runs from the third column line all the way to the end.

What Is Subgrid Used For?

Subgrid lets a grid item use its parent grid’s rows or columns as its own. Its most common use is a row of cards whose titles have different lengths, where subgrid lines up every card’s text and button. It has worked in every major browser since September 2023.

Should I Use CSS Grid or Flexbox?

Grid is usually the better choice when things need to line up across rows and columns at the same time, like a page layout, a gallery, or a form. Flexbox usually wins for a single row or column where the content decides the sizes, like a navigation bar. Most real pages use Grid for the overall layout and Flexbox inside it.

Conclusion

CSS Grid gives us a way to describe a layout the way we'd sketch it on paper. We draw the lines with grid-template-columns and grid-template-rows, size the tracks with fixed lengths and the fr unit, and then either let auto-placement fill things in or put items exactly where we want them using line numbers or named areas. With repeat(auto-fill, minmax()), the grid even works out how many columns fit on its own.

Subgrid is the newest piece, and it's the one that finally lets the insides of our cards line up without fixed heights or JavaScript. If you've ever measured the tallest card title in code just to line up a row of buttons, you now have permission to delete that code.

Before you go, here are a few things you can do:

  1. Ask a question

    Stuck on something, or curious about a detail we skipped? Ask on the forums, and we’ll help you out.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright © KIRUPA 2026 //--