CSS Grid Tutorial: Rows, Columns and the fr Unit
Flexbox handles one direction at a time. CSS Grid handles rows and columns together, which makes it the tool for page layouts, card galleries, dashboards and forms where things must line up in both directions.
Defining tracks
display: grid turns an element into a grid container. Then describe the columns (and optionally the rows):
.layout {
display: grid;
grid-template-columns: 200px 1fr 1fr;
gap: 16px;
}
That creates three columns: a fixed 200-pixel sidebar and two flexible ones. Children are placed into cells automatically, left to right, wrapping onto new rows as needed. You rarely need to define rows; they are created on demand and sized to their content.
The fr unit
fr means "a fraction of the free space". After fixed tracks and gaps are subtracted, the rest is divided by the total number of fr. In the example, a 640-pixel grid has a 160-pixel column, two 1fr columns and 16-pixel gaps. The free space is 640 - 160 - 32 = 448 pixels, so each 1fr column gets 224. The script prints the width of each cell.
Expected page text
Header spans all columns Sidebar Main A Main B header: 640px sidebar: 160px main A: 224px main B: 224px
repeat(4, 1fr) is shorthand for four equal columns.
Placing items
Grid lines are numbered from 1 at the start edge. grid-column: 1 / 3 makes an item span from line 1 to line 3, covering two columns; grid-column: span 2 does the same from wherever the item lands. grid-column: 1 / -1 stretches across the full width, because negative numbers count from the end. In the example, the header uses this to span all three columns.
Responsive cards without media queries
This one line makes a gallery that shows as many columns as fit, each at least 220 pixels wide:
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
minmax(220px, 1fr) says a column may not shrink below 220 pixels but can grow to share the space. auto-fit creates as many columns as fit the container. On a phone you get one column, on a laptop four, with no breakpoints.
Grid or Flexbox?
- Items in a single row or column, sized by their content (a toolbar, tags): Flexbox.
- A layout where rows and columns must align (a page shell, a card gallery, a form): Grid.
They combine well: a Grid page layout whose header uses Flexbox inside is completely normal.
Common mistakes
- Setting
grid-template-columnson the children instead of the container. - Counting columns instead of lines: a three-column grid has four column lines, so full width is
1 / 4or1 / -1. - Forgetting that
frshares only the space left after fixed tracks and gaps.
Summary
display: gridplusgrid-template-columnsdefines the columns.frdivides leftover space;repeat()andminmax()keep definitions short.grid-column: 1 / -1spans the full width.
Quiz: Grid layout