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()
| Unit | Meaning | Example |
|---|---|---|
fr | fraction of free space | 1fr 2fr, second column twice as wide |
repeat() | shorthand | repeat(3, 1fr) equals 1fr 1fr 1fr |
minmax() | min and max | minmax(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 / 31 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
| Question | Answer | Use |
|---|---|---|
| Layout in one direction? | Row OR column | Flex |
| Layout in two directions? | Rows AND columns | Grid |
| Content-driven (unknown count)? | Wrap, distribute | Flex |
| Layout-driven (template)? | Fixed template | Grid |
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; }
- Build the magazine layout above with grid.
- Rebuild the same layout with flex (
flex-wrapplusflex: 1 1 140px) and compare the code. - Make a second version with
grid-template-areasfor a full header, nav, main, footer layout.