🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

CSS Grid: Two-Dimensional Page Layouts

CSS LayoutsđŸŸĸ Free Lesson

CSS Grid

Flexbox arranges items along one axis. CSS Grid places them on two axes at once, which makes it the right tool for page scaffolding, dashboards, image galleries, and any layout you can sketch as rows and columns before the content arrives. Grid's reputation for complexity is undeserved at the basics: a container, a track definition, and a handful of placement rules cover the majority of real layouts.

The mental model is a coordinate system. You define invisible lines — columns numbered left to right, rows top to bottom — and children span rectangles of those lines. Free space, gaps, and auto-placement fill in whatever you leave unspecified.

Defining Tracks

display: grid turns an element into a grid container. Its children become grid items automatically — no wrapper divs, no float hacks.

.dashboard {
  display: grid;
  grid-template-columns: 240px 1fr 1fr;
  grid-template-rows: auto 1fr auto;
  gap: 1rem;
  min-height: 100vh;
}

.dashboard header {
  grid-column: 1 / -1; /* span every column */
}

.dashboard nav {
  grid-row: 2;
}

.dashboard footer {
  grid-column: 1 / -1;
}

The 1 / -1 notation spans from the first line to the last, whatever the column count. Named lines (via grid-template-columns: [main-start] 1fr [main-end]) make such spans self-documenting in larger layouts.

fr Units and the Free-Space Algorithm

The fr unit means "share of the remaining space." After fixed tracks and gaps are subtracted, whatever is left is divided by the sum of fr values and distributed. Crucially, fr tracks can only be as large as their share allows: 240px 1fr never shrinks the sidebar below 240px, but 1fr 1fr splits evenly no matter the content.

A minmax(0, 1fr) track behaves differently from a bare 1fr in one important way — the automatic minimum size of grid tracks defaults to their content's minimum, so a wide table inside a 1fr column can force overflow. Wrapping the track as minmax(0, 1fr) removes that floor, the same lesson flexbox teaches with min-width: 0.

Line Placement vs Area Placement

You can position items by explicit line numbers, by spanning keywords, or by drawing named areas. Line numbers are precise but brittle: insert a column and every index shifts. Named areas keep the layout readable as it evolves.

.page {
  display: grid;
  gap: 1rem;
  grid-template-areas:
    "head  head  head"
    "nav   main  aside"
    "foot  foot  foot";
  grid-template-columns: 200px 1fr 200px;
}

.page > header { grid-area: head; }
.page > nav    { grid-area: nav; }
.page > main   { grid-area: main; }
.page > aside  { grid-area: aside; }
.page > footer { grid-area: foot; }

The template reads like a tiny map of the page. Rearranging the layout becomes an editing task on that map, not a hunt through numeric spans.

Auto-Fill, Auto-Fit, and Responsive Columns

One line can replace a pile of media queries for card galleries:

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 1.25rem;
}

repeat(auto-fill, ...) creates as many tracks as fit, even if some end up empty; auto-fit collapses empty tracks so remaining cards stretch. With minmax(220px, 1fr) the browser measures the container, computes how many 220px minimum tracks fit, and grows them evenly. Resize the window and the column count changes with no breakpoint in sight. Use auto-fill when empty tracks must hold their space (a fixed row of slots), auto-fit when content should absorb it.

FeatureEffect
repeat(3, 1fr)Always exactly three columns
repeat(auto-fill, minmax(200px, 1fr))As many 200px tracks as fit; empties keep space
repeat(auto-fit, minmax(200px, 1fr))Same, but empty tracks collapse
minmax(0, 1fr)Column that may shrink below content width
grid-auto-rows: minmax(100px, auto)Implicit rows at least 100px tall

Gaps, Spanning, and Implicit Tracks

The gap property (and its row and column forms) sets gutters that never double up like adjacent margins do. Tracks you never declared in grid-template-* are implicit tracks, sized by grid-auto-rows and grid-auto-columns; their default auto sizing again respects content minimums, so large implicit rows are another overflow suspect.

Items can span with grid-column: span 2, or with the shorter grid-column: span 2 / -1 tricks. A common dashboard pattern is a summary card that spans two columns of a three-column track list while the rest stay single.

â„šī¸Grid is not just for pages

Component-level layouts are fair game too: a pricing card with a title row, flexible feature list, and pinned footer is a three-row grid. Any time you find yourself nesting flex containers to align a few edges, a small grid usually replaces them with fewer lines.

When Grid Beats Flex (and When It Doesn't)

Choose grid when both axes matter: page shells, photo galleries, calendars, dashboards, pricing tables. Choose flex when one axis drives the design: a row of icon buttons, a navigation bar with space-between groups, a vertical stack that sizes to content. The two compose — a grid cell is a formatting context, so you can run a flex container inside a grid item without conflict.

A hybrid worth memorizing: define the page shell with grid, then let each cell handle its internal spacing with flexbox. This split keeps page structure and component structure in separate, individually editable files.

Subgrid: Aligning Nested Layouts

Grid's headline feature for component work is subgrid — a way for a grid item to hand its internal layout back to the parent's track sizing. Without it, three cards in a row each define their own title area, body area, and footer line, and the cards drift out of alignment whenever one title wraps to an extra line. With subgrid, every card shares the parent's row tracks, and the title band stays the same height across all of them.

The pattern has two halves. The parent defines the tracks, including the internal bands the cards will share, and each child declares which axis it wants to inherit:

.card-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: auto auto 1fr;
  gap: 1rem;
}

.card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 1rem;
}

.card .footer {
  align-self: end;
}

Each card stretches over three parent rows and maps its own children onto those same tracks. Titles align, meta lines align, and footers sit on a shared baseline even when bodies differ in length — the classic equal-height cards with pinned footers problem, solved declaratively.

Subgrid also handles form layouts elegantly. A two-column label-and-field grid can span the whole form, and each field row participates in the same column tracks, so every input starts at the same horizontal position regardless of label length. The property has a modern browser baseline — Chrome, Firefox, and Safari have all shipped it — and the graceful degradation, a plain nested grid, still looks acceptable where support is missing.

💡Debugging grids in DevTools

Every modern browser outlines grid tracks when you select an element with display: grid. Enable the grid overlay in the rendering panel and you get line numbers, named areas, and live track sizes drawn straight onto the page. When an item lands in the wrong cell, the overlay usually shows the answer in seconds: a line number off by one, an implicit row created by an auto-placement surprise, or a gap you forgot existed between two auto-placed items fighting for the same column.

Common Mistakes

A 1fr column that refuses to shrink because of wide content

Fix: Define the track as minmax(0, 1fr) so it can overflow-truncate like a flex item with min-width: 0.

Hard-coding media queries for every column change

Fix: Try repeat(auto-fit, minmax(220px, 1fr)) and let the container size decide.

Scattering grid-column numbers through a large layout

Fix: Name your areas with grid-template-areas and place items with grid-area.

Assuming grid replaces flexbox everywhere

Fix: Grid owns two-dimensional structure; flexbox still wins for content-driven rows.

Key Takeaways

  • Grid places items on two axes at once, which makes it ideal for page scaffolding and galleries.
  • fr distributes leftover space after fixed tracks and gaps are subtracted.
  • minmax(0, 1fr) prevents content minimums from forcing columns wider than their share.
  • grid-template-areas turns the layout into a readable map that survives redesigns.
  • auto-fit with minmax builds responsive card grids without a single media query.
  • Implicit tracks, gaps, and spanning fill in everything the template leaves unspecified.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement