A Complete Guide to CSS Grid Layout
Introduction
CSS Grid is the most important layout revolution in frontend in the past decade. It brought two-dimensional layout from the hack era into the declarative era. This article covers Grid from concepts to practice.
Core Concepts
Grid Container and Items
An element with display: grid becomes a Grid container; its direct children become Grid items.
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: auto;
gap: 16px;
}
Tracks and Cells
- Track: a column or row
- Cell: intersection of a column and row
- Grid line: boundary of a cell
The fr Unit
fr stands for fraction unit, representing shares of remaining space. 1fr 2fr 1fr means dividing space into 4 parts, the middle taking 2.
Practice: Responsive Card Grid
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1rem;
}
auto-fill fills columns automatically based on container width; minmax(280px, 1fr) limits each column to a minimum of 280px and a maximum of evenly distributed remaining space. This is the most concise responsive grid pattern.
Grid vs Flexbox
- Use Flexbox for one-dimensional layouts
- Use Grid for two-dimensional layouts
- When unsure, prefer Grid — it is more powerful
Grid is not a replacement for Flexbox, but a complement. Only by understanding two-dimensional thinking do you truly master modern CSS layout.