In the Flexbox chapters we laid items out along one line: a row or a column. Flexbox is excellent for navigation bars, toolbars and rows of buttons. But a lot of page layouts are really tables of space: a header across the top, a sidebar on the left, content in the middle, a footer at the bottom, or a gallery of cards in neat rows and columns.
For that kind of layout, CSS has a dedicated system: CSS Grid Layout. With Grid you describe the rows and columns once on the parent, and then place children into that structure. In this chapter we learn the core of Grid: the vocabulary, defining tracks, the fr unit, repeat() and minmax(), placing items by line numbers and by named areas, the implicit grid, and alignment. The next chapter, Grid Layout Patterns, uses all of this to build real-world layouts.
What is CSS Grid?
CSS Grid Layout is a two-dimensional layout system. A grid container divides its space into rows and columns, and its children (grid items) are placed into the cells and areas formed by those rows and columns.
The key word is two-dimensional. Flexbox decides sizes along one axis at a time, and each flex line is independent of the others. In a grid, the columns line up across every row and the rows line up across every column, because the grid structure is shared by all items.
Flexbox (1D) Grid (2D)
┌──────┬────────────┬────┐ ┌──────┬──────┬──────┐
│ A │ B │ C │ │ A │ B │ C │
├──────┴──┬─────────┴────┤ ├──────┼──────┼──────┤
│ D │ E │ │ D │ E │ F │
└─────────┴──────────────┘ └──────┴──────┴──────┘
each line sizes itself columns line up in every row
Browser support is not a concern: Grid has worked in every major browser since 2017 and is marked Baseline: widely available on MDN.
Grid Vocabulary
Grid comes with a few terms. Learn them once and the property names will make sense.
column line 1 line 2 line 3 line 4
│ │ │ │
row line 1├────────────┼────────────┼────────────┤
│ cell │ │ │ ← row track 1
row line 2├────────────┼────────────┼────────────┤
│ │ grid area (2×2) │ ← row track 2
│ │ │
row line 3├────────────┤ │
│ │ │ ← row track 3
row line 4├────────────┴────────────┴────────────┘
col track 1 col track 2 col track 3
| Term | Meaning |
|---|---|
| Grid container | The element with display: grid. |
| Grid item | A direct child of the grid container. Grandchildren are not grid items. |
| Grid line | The dividing lines between tracks. They are numbered from 1, starting at the start edge. A grid with 3 columns has 4 column lines. |
| Track | The space between two neighbouring lines: one row or one column. |
| Cell | The intersection of one row and one column; the smallest unit of the grid. |
| Area | Any rectangle of one or more cells. |
| Gap (gutter) | Space between tracks. It exists only between tracks, never on the outside edges. |
Remember: with n tracks there are n + 1 lines. Placement is done using lines, not tracks, which is why spanning "column 1 to 3" covers two columns.
Creating a Grid
Use display: grid on the parent and describe the columns with grid-template-columns:
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
.grid {
display: grid;
grid-template-columns: 150px 150px 150px;
gap: 10px;
}
.grid > div {
background: #dbeafe;
padding: 1rem;
}
Result:
┌───────┐ ┌───────┐ ┌───────┐
│ 1 │ │ 2 │ │ 3 │
└───────┘ └───────┘ └───────┘
┌───────┐ ┌───────┐ ┌───────┐
│ 4 │ │ 5 │ │ 6 │
└───────┘ └───────┘ └───────┘
three 150px columns, 10px gaps
We never said how many rows we wanted. The six items fill the first row left to right, then the browser automatically creates a second row. This automatic behaviour is called auto-placement, and the extra rows form the implicit grid (more on this below).
There is also display: inline-grid. The inside works exactly the same; the only difference is that the container itself behaves like an inline-level box (like inline-block, from The Display Property chapter) instead of a block.
Defining Tracks
Two properties define the explicit grid:
grid-template-columns: one size per column.grid-template-rows: one size per row.
.layout {
display: grid;
grid-template-columns: 200px 400px; /* 2 columns */
grid-template-rows: 80px 300px 60px; /* 3 rows */
}
A track size can be any length (px, rem, %, ...), the keyword auto, the fr unit, or a function such as minmax(). If you leave out grid-template-rows, rows are created automatically and are as tall as their content.
The fr Unit
The
frunit (fraction) represents a share of the free space left in the grid container after fixed-size tracks and gaps have been subtracted.
This is the most useful unit in Grid. Let's work one example out by hand:
.grid {
display: grid;
width: 900px;
grid-template-columns: 200px 1fr 2fr;
gap: 20px;
}
Step 1: container width = 900px
Step 2: subtract fixed tracks (200px) → 700px
Step 3: subtract gaps (2 gaps × 20px = 40) → 660px ← free space
Step 4: total fr = 1 + 2 = 3 → 1fr = 660 ÷ 3 = 220px
Result: columns are 200px, 220px, 440px
Checking in Chrome DevTools, the computed value of grid-template-columns is exactly 200px 220px 440px. Notice that 200 + 220 + 440 + 40 = 900: the grid fits perfectly.
Why not just use percentages?
Percentages ignore gaps. 50% 50% means "half of the container" for each column, and then the gap is added on top:
.grid {
display: grid;
width: 600px;
grid-template-columns: 50% 50%;
gap: 20px;
}
50% of 600 = 300px → 300 + 20 (gap) + 300 = 620px
The grid is 20px wider than its 600px container → it overflows.
With 1fr 1fr the gap is subtracted first, giving two 290px columns that fit exactly. This is why fr is the normal choice for flexible columns.
repeat() and minmax()
repeat()
Writing 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr is painful. repeat(count, tracks) does it for you:
grid-template-columns: repeat(12, 1fr); /* 12 equal columns */
grid-template-columns: repeat(3, 100px 1fr); /* 100px 1fr 100px 1fr 100px 1fr */
grid-template-columns: 250px repeat(2, 1fr); /* can be mixed with other sizes */
The count can also be the keyword auto-fill or auto-fit, which let the browser decide how many columns fit. That trick creates responsive grids without media queries; we study it in detail in Grid Layout Patterns.
minmax()
minmax(min, max) defines a size range for a track: never smaller than min, never larger than max.
.grid {
display: grid;
grid-template-columns: minmax(200px, 300px) 1fr;
grid-template-rows: minmax(100px, auto);
}
The first column grows up to 300px but never shrinks below 200px.
The row is at least 100px tall, but if the content needs more height it grows (
autoas a maximum means "as big as the content needs").
Track sizing keywords
| Value | Meaning |
|---|---|
200px, 10rem | Fixed size. |
25% | Percentage of the container's size (gaps not considered). |
1fr | A share of the leftover free space. |
auto | Sized by content; when there are no fr tracks, auto tracks also stretch to fill leftover space. |
min-content | The smallest size the content can take without overflowing (e.g. the longest word). |
max-content | The size the content wants with no wrapping at all. |
fit-content(300px) | Like auto, but capped at 300px. (The one exception: if the content cannot get narrower than 300px, e.g. a long unbreakable word, the track still grows to that minimum.) |
minmax(a, b) | Any size between a and b. |
A popular header pattern combines auto and fr: grid-template-columns: auto 1fr auto; gives a logo column and a login column exactly as wide as their content, and the middle column takes everything else.
Gaps
.grid {
row-gap: 24px;
column-gap: 16px;
/* or the shorthand: gap: <row-gap> <column-gap> */
gap: 24px 16px;
}
A single value (gap: 16px) is used for both directions. Gaps only appear between tracks; if you want space around the outside, use padding on the container. You may still see the old names grid-gap, grid-row-gap and grid-column-gap in older code; browsers still accept them as aliases, but use gap in new code.
Placing Items with Line Numbers
By default every item takes the next free cell. To put an item somewhere specific, tell it which lines it starts and ends at:
.item {
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 2;
grid-row-end: 3;
}
/* the same thing with shorthands: start / end */
.item {
grid-column: 1 / 3;
grid-row: 2 / 3;
}
The item starts at column line 1 and ends at column line 3, so it covers columns 1 and 2. It sits in row 2.
span
Often you care about how many tracks to cover, not the exact end line. Use span:
.wide { grid-column: span 2; } /* 2 columns, wherever it lands */
.a { grid-column: 2 / span 2; } /* start at line 2, cover 2 columns → ends at line 4 */
.b { grid-column: span 2 / 5; } /* end at line 5, cover 2 columns → starts at line 3 */
If you give only a start (grid-column: 2), the item spans one track.
Negative line numbers
Lines can also be counted from the end: -1 is the last line, -2 the one before it, and so on.
.full-width {
grid-column: 1 / -1; /* from the first line to the last line */
}
This is the standard way to make an item stretch across all columns, whatever their number. One catch: negative numbers count from the end of the explicit grid (the tracks you defined in grid-template-columns), not of any extra implicit columns.
Worked example: a 4-column grid
.grid {
display: grid;
grid-template-columns: repeat(4, 100px);
}
.a { grid-column: 2 / span 2; }
.b { grid-column: span 2 / 5; }
lines: 1 2 3 4 5
row 1: │ │ aaaaaaaaaaaaa │ │ a: lines 2 → 4 (x = 100px, width 200px)
row 2: │ │ │ bbbbbbbbbbbbb │ b: lines 3 → 5 (x = 200px, width 200px)
b moves to row 2 because its columns overlap with a in row 1, and auto-placement never lets items overlap on its own. (You can make items overlap deliberately by giving them the same lines; that is shown in Grid Layout Patterns.)
Named Areas: grid-template-areas
Line numbers work, but for page layouts there is a far more readable way. You draw the layout as text, giving every cell a name:
<div class="page">
<header class="header">Header</header>
<aside class="sidebar">Sidebar</aside>
<main class="main">Main content</main>
<footer class="footer">Footer</footer>
</div>
.page {
display: grid;
grid-template-columns: 150px 1fr;
grid-template-rows: 50px 200px 40px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
With the container 600px wide, the result is:
┌──────────────────────────────────────┐
│ Header 600 × 50 │
├──────────┬───────────────────────────┤
│ Sidebar │ Main content │
│ 150×200 │ 450 × 200 │
├──────────┴───────────────────────────┤
│ Footer 600 × 40 │
└──────────────────────────────────────┘
Each quoted string is one row; each word is one cell. Repeating a name across cells makes that area span them. The rules are:
Every row string must have the same number of cells.
Each named area must form a rectangle. An L-shape or a name split into two separate places makes the whole declaration invalid, and it is ignored.
Use a dot
.(or several dots like...) for an empty cell.The
grid-areaname on the item is a plain identifier, not a string:grid-area: header;, notgrid-area: "header";.
The big advantage: to rearrange the page (say, put the sidebar on the right), you change only the strings. The HTML order stays the same. In Responsive Design & Media Queries we will use exactly this to switch layouts on small screens.
Accessibility note: Grid lets the visual order differ from the source order, but screen readers and the Tab key follow the source order. Keep your HTML in a sensible reading order and use Grid for presentation, not to fix a badly ordered document.
grid-area as a line shorthand
grid-area can also take four line numbers, in the order row-start / column-start / row-end / column-end:
.box { grid-area: 1 / 2 / 3 / 4; }
/* same as: grid-row: 1 / 3; grid-column: 2 / 4; */
The order (rows first, then columns; starts then ends) is a common exam trap.
The Implicit Grid
The explicit grid is made of the tracks you define with
grid-template-*. When items are placed outside it, or there are more items than cells, the browser adds extra tracks automatically. These form the implicit grid.
You control the size of the implicit tracks with grid-auto-rows and grid-auto-columns:
.grid {
display: grid;
grid-template-columns: 100px 100px;
grid-template-rows: 50px; /* explicit: just one row */
grid-auto-rows: 30px; /* every extra row: 30px */
}
With five items, Chrome reports the rows as 50px 30px 30px:
┌─────┬─────┐
│ 1 │ 2 │ 50px ← explicit row
├─────┼─────┤
│ 3 │ 4 │ 30px ← implicit
├─────┼─────┤
│ 5 │ │ 30px ← implicit
└─────┴─────┘
A very common line is grid-auto-rows: minmax(100px, auto);: every automatic row is at least 100px tall and grows if the content needs more.
grid-auto-flow
grid-auto-flow decides how auto-placement fills the grid:
| Value | Behaviour |
|---|---|
row (default) | Fill each row, then add a new row. |
column | Fill each column top to bottom, then add a new column. |
dense (with row or column) | Go back and fill earlier holes with later, smaller items. |
Let's see dense in action. Three 100px columns; item 3 spans two columns:
.grid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-auto-rows: 40px;
}
.wide { grid-column: span 2; } /* applied to item 3 */
grid-auto-flow: row (default) grid-auto-flow: row dense
┌─────┬─────┬─────┐ ┌─────┬─────┬─────┐
│ 1 │ 2 │ │ ← hole │ 1 │ 2 │ 4 │
├─────┴─────┼─────┤ ├─────┴─────┼─────┤
│ 3 │ 4 │ │ 3 │ │
└───────────┴─────┘ └───────────┴─────┘
Without dense, item 3 doesn't fit in the single cell left in row 1, so it moves to row 2 and leaves a hole. With dense, item 4 fills that hole. The catch: item 4 now appears before item 3 visually, while the source order is unchanged. That is fine for an image gallery, but bad for content that must be read in order.
Aligning in Grid
Grid uses the same alignment properties you met in Flexbox. Two ideas keep them apart:
justify- = along the row direction (inline axis, horizontal in English). align- = along the column direction (block axis, vertical).
-items / -self move an item inside its own cell. -content moves the whole set of tracks inside the container, which only matters when the tracks are smaller than the container.
| Property | Set on | What moves | Axis |
|---|---|---|---|
justify-items | container | every item, inside its cell | row (inline) |
align-items | container | every item, inside its cell | column (block) |
justify-self | item | one item | row (inline) |
align-self | item | one item | column (block) |
justify-content | container | all tracks together | row (inline) |
align-content | container | all tracks together | column (block) |
place-items | container | shorthand: align-items justify-items | both |
place-content | container | shorthand: align-content justify-content | both |
The default for items is stretch: an item fills its whole cell. That is why grid items in the same row look equally tall without any extra work.
.grid {
display: grid;
width: 400px;
height: 200px;
grid-template-columns: 100px 100px;
grid-template-rows: 50px 50px;
justify-content: space-between; /* columns pushed to the left and right edges */
align-content: center; /* the two rows sit in the vertical middle */
place-items: center end; /* inside each cell: vertically centred, at the right end */
}
With four short items (1 to 4), Chrome gives this result. The boxes are the cells; each item shrinks to the width of its text and sits at the right end of its cell, vertically centred:
400 × 200 container
┌──────────────────────────────────────────┐
│ │ 50px empty
│ ┌─────────┐ ┌─────────┐ │
│ │ 1 │ │ 2 │ │ row 1 (y = 50 to 100)
│ ├─────────┤ ├─────────┤ │
│ │ 3 │ │ 4 │ │ row 2 (y = 100 to 150)
│ └─────────┘ └─────────┘ │
│ │ 50px empty
└──────────────────────────────────────────┘
column 1 at x = 0, column 2 at x = 300 (space-between)
Remember that place-items takes the block (align) value first, then the inline (justify) value. And the famous two-line centring trick from Flexbox has a Grid version too:
.center-me {
display: grid;
place-items: center; /* child is centred both ways */
}
A Common Surprise: 1fr Is Not Always Equal
You might expect 1fr 1fr to always give two equal columns. Now put something in the first column that cannot get narrower than 450px: a 450px-wide image, a wide table, or a very long word with no break points:
.grid {
display: grid;
width: 600px;
grid-template-columns: 1fr 1fr;
}
In Chrome the columns come out as 450px 150px, not 300px each. Why? Because 1fr is really minmax(auto, 1fr): the column is never allowed to become narrower than its minimum content size, which here is 450px. The browser first tries 300px each, sees that column 1 can't be that small, freezes it at 450px, and gives the remaining 600 − 450 = 150px to column 2. The fix is to allow the minimum to be zero:
.grid {
grid-template-columns: repeat(2, minmax(0, 1fr)); /* truly equal: 300px + 300px */
}
Now the columns are exactly 300px each (checked in Chrome). The wide content will overflow its own cell, so add overflow-wrap: anywhere; (or hide the overflow) on the content as well. The same problem shows up with wide images, <pre> blocks and tables inside grid items.
Grid vs Flexbox
| Aspect | Flexbox | Grid |
|---|---|---|
| Dimensions | One (row or column) | Two (rows and columns) |
| Approach | Content-out: items decide their size, the line adapts | Layout-in: the container defines tracks, items fit into them |
| Alignment across lines | Each wrapped line is independent | Columns line up in every row |
| Placing an item at a specific spot | Only via order | Any line, span or named area |
| Overlapping items | Not without positioning | Yes, place two items in the same cells |
| Typical use | Navbars, button groups, centring, media objects | Page layouts, card galleries, dashboards, forms |
They are not competitors. A real page usually uses Grid for the overall layout and Flexbox inside the components (for example, a grid of cards where each card's footer is a flex row).
Common Mistakes
Expecting grandchildren to be grid items. Only direct children are placed on the grid. (The
subgridvalue, shown in Grid Layout Patterns, lets nested elements share the parent's tracks.)Confusing lines with tracks.
grid-column: 1 / 3covers two columns, not three.Using percentages with gaps.
50% 50%plus a gap overflows; use1fr 1fr.Non-rectangular areas. An area name that forms an L-shape makes the whole
grid-template-areasdeclaration invalid.Quoting the area name on the item. It is
grid-area: main;, notgrid-area: "main";.Expecting
1 / -1to reach implicit columns.-1is the last line of the explicit grid.Getting the
grid-areafour-value order wrong. It is row-start / column-start / row-end / column-end.Blow-outs from long content. Use
minmax(0, 1fr)when columns must stay equal.
Interview & Exam Questions
1. A grid is 1000px wide with grid-template-columns: 100px 1fr 3fr; and gap: 30px. What are the column widths?
Free space = 1000 − 100 − (2 × 30) = 840px. Total fr = 4, so 1fr = 210px. Columns: 100px, 210px, 630px. Check: 100 + 210 + 630 + 60 = 1000.
2. What is the difference between the explicit and the implicit grid?
The explicit grid is the set of tracks you define with grid-template-columns, grid-template-rows and grid-template-areas. The implicit grid is made of extra tracks the browser creates automatically when items don't fit in, or are placed outside, the explicit grid. Implicit track sizes are set with grid-auto-rows and grid-auto-columns.
3. How many column lines does grid-template-columns: repeat(4, 1fr) create, and how do you make an item span all of them?
Four columns have five lines. Use grid-column: 1 / -1; (or 1 / 5, or span 4).
4. What does grid-area: 2 / 1 / 4 / 3 mean?
Row-start 2, column-start 1, row-end 4, column-end 3. The item covers rows 2 and 3 and columns 1 and 2, a 2×2 block.
5. Why can 1fr 1fr produce unequal columns, and how do you fix it?
1fr has an automatic minimum (minmax(auto, 1fr)), so a track can't shrink below its content's minimum size, such as a long word or a wide image. Use minmax(0, 1fr) to allow the track to shrink, and handle the overflow inside the item.
6. What is the difference between justify-items and justify-content in Grid?
justify-items aligns each item inside its own cell along the inline (row) axis. justify-content moves the whole group of column tracks inside the container, and only has a visible effect when the tracks are narrower than the container.
7. When would you choose Grid over Flexbox?
When the layout is two-dimensional and items must line up in both rows and columns (page layouts, galleries, dashboards), or when you need to place items at exact positions or overlap them. For a single row or column of items whose size depends on their content, Flexbox is usually simpler.
Summary
Grid is a two-dimensional layout system:
display: gridon the parent, direct children become grid items.Tracks are defined with
grid-template-columns/grid-template-rows;ntracks haven + 1lines.frshares the free space left after fixed tracks and gaps; prefer it to percentages.repeat()avoids repetition;minmax()sets a size range;minmax(0, 1fr)gives truly equal columns.Place items with lines (
grid-column: 1 / 3,span 2,1 / -1) or with named areas (grid-template-areas+grid-area).Extra tracks form the implicit grid, sized with
grid-auto-rows/grid-auto-columns;grid-auto-flow: densefills holes.justify-*works on the row axis,align-*on the column axis;-items/-selfalign inside cells,-contentmoves the tracks.
You now know the building blocks. In Grid Layout Patterns we put them together into layouts you will build again and again: responsive card galleries, the holy grail page, full-bleed articles, overlapping heroes and subgrid-aligned cards.