CSS Grid Fundamentals
CSS Grid is the most powerful layout system in CSS. Unlike Flexbox (one-dimensional), Grid works in two dimensions — rows AND columns simultaneously. It lets you create complex page layouts, dashboard grids, and magazine-style designs without hacky CSS.
Grid Container Properties
- display: grid — Converts element to grid container. Children become grid items automatically
- grid-template-columns — Define columns: grid-template-columns: 200px 1fr 1fr (fixed + flexible)
- grid-template-rows — Define rows: grid-template-rows: auto 1fr auto (header + content + footer)
- gap — Space between cells: gap: 20px or row-gap: 20px column-gap: 16px
- fr unit — Fractional unit. 1fr = 1 share of remaining space. 2fr 1fr = 66% + 33%
- repeat() — Shorthand: repeat(3, 1fr) = 1fr 1fr 1fr. repeat(auto-fit, minmax(250px, 1fr)) for responsive grids
- minmax() — Set min and max sizes: minmax(200px, 1fr) = at least 200px, takes remaining space
Grid Layout Code
/* Basic page layout */
.page {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: 60px 1fr 50px;
min-height: 100vh;
}
/* Responsive card grid (no media queries!) */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 24px;
}
/* Fixed + flexible columns */
.sidebar-layout {
display: grid;
grid-template-columns: 250px 1fr;
gap: 24px;
}
/* Equal columns */
.three-cols {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}Try It Yourself: CSS Grid Dashboard
Tip
The repeat(auto-fit, minmax(280px, 1fr)) pattern is the single most powerful CSS Grid shortcut. It creates a responsive grid that automatically adjusts from 1 column on mobile to many columns on desktop — with zero media queries. Memorize this pattern.
Grid handles two-dimensional layouts — rows AND columns simultaneously
Common Mistake
Confusing the fr unit with percentage. 1fr is not 100% — it's one share of the REMAINING space after fixed-size columns are allocated. In 'grid-template-columns: 200px 1fr', the 1fr column gets everything left after the 200px column takes its space.
Practice Task
Build a dashboard widget grid: (1) display: grid with repeat(3, 1fr) and gap: 20px, (2) Make one widget span 2 columns with grid-column: span 2, (3) Change to repeat(auto-fit, minmax(250px, 1fr)) and resize the browser. Compare: how many columns appear at 600px, 900px, and 1200px wide?
Quick Quiz
Key Takeaways
- CSS Grid is the most powerful layout system in CSS.
- display: grid — Converts element to grid container. Children become grid items automatically
- grid-template-columns — Define columns: grid-template-columns: 200px 1fr 1fr (fixed + flexible)
- grid-template-rows — Define rows: grid-template-rows: auto 1fr auto (header + content + footer)