CSS: CSS Grid Container
Last updated: 2026-10-13
CSS Grid is a powerful two-dimensional layout system that lets you control rows and columns simultaneously.
1. Grid Container Properties
(1) Quick Reference
| Property | Values | Purpose |
|---|---|---|
display: grid |
— | Creates grid container |
grid-template-columns |
100px 1fr 2fr, repeat(3, 1fr) |
Column definitions |
grid-template-rows |
100px auto, repeat(3, 100px) |
Row definitions |
gap |
10px, 10px 20px |
Gap between items |
grid-template-areas |
"header header" "main aside" |
Named grid areas |
2. fr Unit
The fr unit distributes remaining space proportionally:
▶ Example
▶ Try it Yourself3. repeat()
The repeat() function reduces repetition:
▶ Example
▶ Try it Yourself4. minmax() + auto-fill/auto-fit
Creates responsive grids that automatically adjust column count:
▶ Example
▶ Try it Yourselfauto-fill vs auto-fit:
auto-fill: Creates as many columns as fit, even if emptyauto-fit: Same as auto-fill, but collapses empty columns
5. grid-template-areas
Define layout with named areas:
▶ Example
▶ Try it Yourself❓ FAQ
Q How to choose between Grid and Flexbox?
A One-dimensional (single row or column) uses Flexbox, two-dimensional (simultaneous row and column control) uses Grid. Most pages use both: Grid for overall page skeleton, Flexbox for local arrangements. Using both on one page is completely normal.
Q What's the difference between fr units and percentages?
A
fr distributes remaining space, percentages distribute total width. With gap, fr automatically deducts gap before calculating proportions, percentages don't. 1fr 1fr 1fr with gap is still perfect thirds, while 33.33% 33.33% 33.33% overflows.Q How to use grid-template-areas?
A Define layout with named areas:
grid-template-areas: "header header" "sidebar main" "footer footer"; then assign children with grid-area: header. To change layout, just adjust the string template — no need to reposition children.📖 Summary
- Grid is a powerful two-dimensional layout system
- Define grid structure with
grid-template-columnsandgrid-template-rows - Use
frunit for proportional space distribution - Create flexible grids with
repeat(),minmax() gapsets spacing;auto-fill/auto-fitwithminmaxcreates truly responsive grids
📝 Exercises
Basic
- Create a 3×3 grid container, each cell 100px×100px, 10px gap.
- Use
1frunit for a "two-column" layout (left 1fr, right 3fr).
Intermediate
- Create an auto-adapting card grid with
repeat(auto-fill, minmax(150px, 1fr))— resize browser to see columns change. - Create a "classic three-row two-column" layout: header (spanning two columns), left menu, right content, footer (spanning two columns).
Challenge
- Create a responsive image gallery: desktop 4 columns, tablet 2 columns, mobile 1 column, using
auto-fill+minmax. - Use
grid-template-areasfor a complete blog layout (header, navigation, main content, sidebar, footer).