Topic 6 of 30
Grid
Overview
CSS Grid is a two-dimensional layout system that lets you design complex web layouts with rows AND columns simultaneously. It is ideal for overall page layouts, dashboards, and image galleries.
Syntax
css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
grid-template-rows: auto;
gap: 24px;
}
/* Named template areas */
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-columns: 250px 1fr 1fr;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }Common Pitfalls
- Grid and Flexbox are complementary — use Grid for 2D (rows + columns) layouts, Flexbox for 1D (row OR column).
- fr (fractional unit) distributes remaining space AFTER fixed columns — 1fr 1fr doesn't mean 50/50 if there's a gap.
- Interview tip: grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)) creates a responsive grid with no media queries.
Real-World Example
A dashboard layout using named grid template areas:
example
css
.dashboard {
display: grid;
grid-template-areas:
"nav nav nav"
"sidebar content content"
"sidebar content content";
grid-template-columns: 240px 1fr;
grid-template-rows: 64px 1fr;
height: 100vh;
}
.dashboard-nav { grid-area: nav; background: #111; }
.dashboard-sidebar { grid-area: sidebar; background: #1a1a1a; overflow-y: auto; }
.dashboard-content { grid-area: content; padding: 24px; overflow-y: auto; }
/* Responsive — stack on mobile */
@media (max-width: 768px) {
.dashboard {
grid-template-areas:
"nav"
"content";
grid-template-columns: 1fr;
}
.dashboard-sidebar { display: none; }
}