What CSS Grid is
CSS Grid is the most powerful layout system in CSS today. It lets you build two-dimensional grids with explicit columns and rows, control alignment, and pin elements to specific positions. It is the right tool for page layouts, dashboards, galleries and any structure that needs fine control on two axes.
Key concepts
- grid-template-columns: sets number and size of columns.
- grid-template-rows: sets number and size of rows (optional).
- gap: space between cells.
- grid-template-areas: assigns names to grid regions.
- grid-column / grid-row: positions an item across specific tracks.
The fr unit
fr (fraction) represents a fraction of the space available after subtracting gaps and fixed sizes. 1fr 2fr 1fr splits in 1:2:1 ratio. It is the right unit for responsive grids because it adapts without manual percentage math.
Useful patterns
/* 3 equal columns */
grid-template-columns: repeat(3, 1fr);
/* min 200px, max 1fr, auto fill */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* 250px sidebar + fluid content */
grid-template-columns: 250px 1fr; The repeat(auto-fill, minmax(200px, 1fr)) pattern is the magic formula for galleries: the grid adds columns as space allows while keeping each item above a sensible minimum.
Grid template areas
For complex layouts (header / sidebar / main / footer), grid-template-areas is the most readable option:
grid-template-areas:
"header header"
"sidebar main"
"footer footer"; Then assign each element with grid-area: header;. Changing the layout on mobile means rewriting the areas, not reordering HTML.
Grid vs Flexbox
Grid is two-dimensional: rows and columns at once. Flexbox is one-dimensional: items flow in a single direction. For a product grid, Grid. For a horizontal toolbar, Flexbox. In large layouts you use both: Grid for the macro structure, Flexbox inside each cell.
Responsive
Grid enables very concise media queries. Going from three columns to one on mobile is one line: grid-template-columns: 1fr;. Combined with auto-fill and minmax, you can have grids that adapt without explicit media queries.