10: Grid

Flexbox handles one dimension. Grid handles two. If you can think in rows and columns at the same time, you can use grid.

Grid in 30 seconds

1
2
3
4
5
6
.parent {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
  gap: 8px;
}

1fr means one fraction of the available space. Three 1fr values split it into thirds.


Units: fr, repeat(), minmax()

UnitMeaningExample
frfraction of free space1fr 2fr, second column twice as wide
repeat()shorthandrepeat(3, 1fr) equals 1fr 1fr 1fr
minmax()min and maxminmax(200px, 1fr), at least 200px

repeat(3, 1fr), equal columns

1fr1fr1fr

1fr 2fr, proportional

1fr2fr

200px 1fr, fixed plus flexible

200px1fr
/* equal thirds */
.grid { grid-template-columns: repeat(3, 1fr); }

/* sidebar + main */
.layout { grid-template-columns: 200px 1fr; }

/* responsive without media query, see below */
.auto { grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); }

Centering callback: place-items vs. place-content

Both came up in Module 7. Now you can see why they exist.

place-items: center

child in cell

centers the child inside its grid cell

place-content: center

grid centered

centers the entire grid inside the parent


Spanning and areas

grid-column / grid-row

spans 2 columns, grid-column: 1 / 3
1 col
1
2
3
.hero { grid-column: 1 / 3; } /* span from line 1 to 3 */
.full { grid-column: 1 / -1; } /* span all columns */

grid-template-areas: named layout

header
nav
main content
footer
.page {
  display: grid;
  grid-template-columns: 180px 1fr;
  grid-template-areas:
    "hd hd"
    "nav main"
    "ft ft";
}
.page header { grid-area: hd; }
.page nav    { grid-area: nav; }
.page main   { grid-area: main; }
.page footer { grid-area: ft; }

Flex vs. Grid: a decision guide

QuestionAnswerUse
Layout in one direction?Row OR columnFlex
Layout in two directions?Rows AND columnsGrid
Content-driven (unknown count)?Wrap, distributeFlex
Layout-driven (template)?Fixed templateGrid
They compose: Use grid for page layout and flex for the components inside it. A grid cell can be a flex container, and a flex item can be a grid.

Live demo: a magazine layout, flex vs. grid

Resize the window to see grid's auto-fit responsiveness for free.

Featured, spans 2 columns
Story A
Story B
Story C
Story D
.mag {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 8px;
}
.mag .featured { grid-column: span 2; }
Exercise: Magazine layout, flex vs. grid (20 min)
  1. Build the magazine layout above with grid.
  2. Rebuild the same layout with flex (flex-wrap plus flex: 1 1 140px) and compare the code.
  3. Make a second version with grid-template-areas for a full header, nav, main, footer layout.
Prev9: Flexbox Next11: Position & Stacking