
Mastering CSS Grid Layout
Introduction to CSS Grid
CSS Grid Layout is a two-dimensional layout system that has revolutionized how we design web layouts. Unlike Flexbox, which is primarily one-dimensional, Grid allows you to control both rows and columns simultaneously.
Basic Grid Concepts
- Grid Container and Grid Items
- Grid Lines, Tracks, and Cells
- Grid Areas
- Explicit vs. Implicit Grids
Creating Your First Grid
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto 1fr auto;
gap: 20px;
}
Advanced Grid Techniques
Once you understand the basics, you can leverage these advanced techniques:
- Named Grid Areas
- Auto-placement Algorithms
- Responsive Grids with minmax()
- Grid Template Areas
- Alignment and Justification
Real-World Example
.dashboard {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"sidebar stats stats"
"footer footer footer";
grid-template-columns: 250px 1fr 1fr;
grid-template-rows: auto 1fr auto auto;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.stats { grid-area: stats; }
.footer { grid-area: footer; }
Browser Support and Fallbacks
CSS Grid is now supported in all modern browsers, but it's still good practice to provide fallbacks for older browsers. Feature queries using @supports can help with this.