Introduction to CSS Grid
Introduction to CSS Grid
CSS Grid is designed for aligning elements in two dimensions: rows and columns can be controlled together.
What you’ll learn
- Distinguish Grid tracks, cells and items.
- Identify where two-dimensional layout helps.
- Create a basic grid container with repeated columns.
Understand the concept
Set display:grid on a container, then define columns and optional rows. Direct children become grid items. The grid tracks form cells; an item can occupy one cell or span multiple cells.
Unlike Flexbox, which flows primarily along one main axis, Grid places items relative to a shared row-and-column structure. Grid is useful for card collections, page regions, dashboards and aligned forms.
Visualize the relationship
Define a three-column grid
Each child occupies one grid cell.
HTML
<div class="grid-sample"><div>Alpha</div><div>Beta</div><div>Gamma</div><div>Delta</div><div>Epsilon</div></div>CSS
.grid-sample { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; max-width: 385px; background: #f1f5f9; padding: 10px; }
.grid-sample div { padding: 16px 8px; background: #bfdbfe; border-radius: 6px; text-align: center; }Rendered output
Observe: The first three items fill row one and the next two fill row two.
Use unequal tracks intentionally
Give the main area two fractional shares and the sidebar one.
HTML
<div class="grid-sample"><section>Reading area</section><aside>Sidebar</aside></div>CSS
.grid-sample { display: grid; grid-template-columns: 2fr 1fr; gap: 12px; max-width: 385px; }
.grid-sample section, .grid-sample aside { padding: 18px 10px; background: #ccfbf1; border-radius: 7px; }
.grid-sample aside { background: #dbeafe; }Rendered output
Observe: The main track is about twice the width of the sidebar track after gaps are accounted for.
Explain the result
A grid container defines shared tracks; auto-placement fills available cells with its direct children in source order.
Compare the two examples: identify the selector, each changed property, and which visible part of the output proves that the CSS took effect.
Common mistakes to avoid
- Grid only makes immediate children grid items; nested elements do not automatically join the parent grid.
- Grid item content may enforce minimum track sizes and create overflow unless you plan constraints.
Try it yourself
Change the first example to two columns. Predict which row Epsilon enters and compare with the rendered layout.
Before changing the code, predict what will change. Then verify by checking the rendered result.
Check your understanding
What you should remember
Use Grid when content benefits from shared row and column alignment.
Revisit the rendered examples if the rule still feels abstract. Change one declaration at a time so you can connect cause and effect.
Reaching the recap and completing the quizzes are separate milestones.