How to Use CSS Grid: A Practical Layout Guide
CSS Grid is a two-dimensional layout system that lets you define rows and columns simultaneously. It replaces float hacks, clearfixes, and complex Flexbox nesting with a clean, declarative syntax. If Flexbox is for components, Grid is for page layouts.
- Build responsive page layouts with CSS Grid.
- Covers your first grid.
- Covers named template areas.
- Covers responsive grids without media queries.
- Covers grid alignment.
Your First Grid
Define a grid container and specify columns:
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 16px;
}
This creates a three-column grid with equal-width columns and 16px gaps between items. fr (fraction) units distribute available space proportionally โ 1fr 1fr 1fr means each column gets one-third of the container width.
Named Template Areas
Grid template areas let you design layouts visually in your CSS:
gap instead of margin hacks for flexbox spacing. It keeps layout code cleaner and is supported in all modern browsers..layout {
display: grid;
grid-template-areas:
'header header header'
'sidebar main main'
'footer footer footer';
grid-template-columns: 250px 1fr 1fr;
grid-template-rows: auto 1fr auto;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
This creates a classic layout with a full-width header, a sidebar, a main content area, and a full-width footer. The ASCII art in grid-template-areas maps directly to the visual layout.
Responsive Grids Without Media Queries
The auto-fit and minmax() combination creates responsive grids that adapt without any media queries:
width, height, top, or left. These trigger layout recalculations on every frame and can drop performance below 60fps..responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
}
Items are at least 280px wide. As the container shrinks, items automatically wrap to new rows. As it grows, more columns appear. This single line replaces 10+ lines of Flexbox with media queries.
Grid Alignment
Grid offers four alignment properties: justify-items (horizontal alignment of items within their cells), align-items (vertical alignment), justify-content (horizontal distribution of the grid within its container), align-content (vertical distribution of rows). The most useful pattern is place-items: center โ a shorthand that centers items both horizontally and vertically within their grid cells. The Grid Generator tool lets you build grid layouts visually, adjust columns, rows, and gaps, then export the CSS.