CSS Grid
A two-dimensional layout system for the web that handles both rows and columns simultaneously.
Detailed Explanation
Unlike Flexbox, which is primarily for one-dimensional layouts (rows OR columns), CSS Grid is designed for complex, two-dimensional structures. It allows developers to define rigid grid areas and place items precisely within them. Grid is 'outside-in', you define the container's structure first and then place content into it. It is perfect for full-page layouts and complex card galleries.
Quick Summary
CSS Grid is a two-dimensional layout system for the web. You declare the rows and columns of a container once, then place children into named or numbered cells with a few lines of CSS , replacing the float, table, and Flexbox hacks of earlier eras.
Key Takeaways
- grid-template-columns and grid-template-rows describe the track structure; fr units distribute remaining space.
- Children can span multiple cells with grid-column: span N or by referencing named lines and areas.
- auto-fill and auto-fit with minmax() create responsive grids without media queries.
- Grid items can be placed out of source order with grid-column / grid-row , useful but risky for accessibility.
- subgrid lets a child grid align with its parent's tracks, which solves long-standing alignment issues in card layouts.
When to use it
- Full-page application shells with header, sidebar, main, and footer regions.
- Photo galleries and product catalogues where items align both vertically and horizontally.
- Calendar views and timetables that must align on both axes.
- Magazine-style layouts with mixed column counts and overlapping content.
Common Mistakes
- Using fixed pixel tracks instead of fr units, then needing media queries for every breakpoint.
- Reaching for Grid for a simple row of buttons where Flexbox is enough.
- Reordering items visually with grid placement and breaking keyboard navigation order.
- Forgetting that minmax(0, 1fr) is needed to prevent content from forcing tracks wider than expected.
CSS Grid, Frequently Asked
Is CSS Grid a replacement for Flexbox?
No , they solve different problems. Grid is for two-dimensional layouts where rows and columns matter together. Flexbox is for one-dimensional layouts. Real apps use both, often nested inside one another.
What does fr mean?
fr is a fractional unit that represents a share of the remaining space in the grid container. grid-template-columns: 1fr 2fr creates two columns where the second is twice as wide as the first, after fixed-size tracks are subtracted.
What is subgrid?
subgrid lets a nested grid inherit its parent's track sizes so children at different nesting levels align with each other. It is supported in every modern browser since 2023 and removes a major class of CSS hacks.