CSS Grid
CSS Grid provides a native two-dimensional layout system, eliminating the need for float-based layouts and complex flexbox workarounds.
The Old Way
Section titled “The Old Way”/* Float-based grid */.container { overflow: hidden; /* clearfix */}
.row::after { content: ''; display: table; clear: both;}
.column { float: left; width: 33.333%; padding: 0 15px; box-sizing: border-box;}
.column:nth-child(3n + 1) { clear: left;}
/* Responsive adjustments */@media (max-width: 768px) { .column { width: 50%; } .column:nth-child(3n + 1) { clear: none; } .column:nth-child(2n + 1) { clear: left; }}Problems:
- Requires clearfix hacks
- Manual width calculations with percentages
- Complex nth-child selectors for row clearing
- No native gap/gutter support
- Cannot easily create unequal column layouts
The Modern Way
Section titled “The Modern Way”.container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 30px;}
/* Responsive adjustments */@media (max-width: 768px) { .container { grid-template-columns: repeat(2, 1fr); }}Benefits:
- No clearfix needed
- Built-in gap support
- Fractional units (
fr) for flexible sizing - Simple responsive changes
- Clean, declarative syntax
Advanced Patterns
Section titled “Advanced Patterns”Named Grid Areas
Section titled “Named Grid Areas”.page { display: grid; grid-template-areas: 'header header header' 'nav main aside' 'footer footer footer'; grid-template-columns: 200px 1fr 200px; grid-template-rows: auto 1fr auto; min-height: 100vh;}
.header { grid-area: header;}.nav { grid-area: nav;}.main { grid-area: main;}.aside { grid-area: aside;}.footer { grid-area: footer;}Auto-Fit Responsive Grid
Section titled “Auto-Fit Responsive Grid”.card-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;}Cards automatically wrap and fill available space—no media queries needed.
Subgrid
Section titled “Subgrid”.parent { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;}
.child { display: grid; grid-column: span 2; grid-template-columns: subgrid; /* Inherits parent's column tracks */}Browser Support
Section titled “Browser Support”Supported in all modern browsers. See caniuse.com/css-grid.
Subgrid has slightly less support. See caniuse.com/css-subgrid.
Performance Considerations
Section titled “Performance Considerations”- Grid layout is hardware-accelerated
- Avoid deeply nested grids for best performance
- Use
grid-template-areasfor complex layouts—easier to maintain auto-fitandauto-fillare computed at layout time
When to Use
Section titled “When to Use”Use CSS Grid when:
- Building two-dimensional layouts (rows AND columns)
- Creating complex page structures
- You need built-in gap/gutter support
- Building card grids with equal-height items
- Layout depends on both row and column positioning
Use Flexbox when:
- One-dimensional layout (row OR column)
- Content size should determine layout
- You need to align items within a container