CSS Grid Fundamentals
Learning Objectives
- Understand grid containers, tracks, lines and cells.
- Define columns and rows.
- Use fr, repeat() and gap.
- Place items across grid lines.
1. Enable Grid
.grid {
display: grid;
}A grid container establishes a two-dimensional layout system. Its direct children become grid items.
2. Define Columns and Rows
.grid {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: 100px auto;
gap: 16px;
}Grid tracks are rows or columns. Grid lines bound tracks, and the spaces where rows and columns intersect are grid cells.
3. The fr Unit
.layout {
display: grid;
grid-template-columns: 1fr 2fr;
}The fr unit represents a fraction of available space in the grid track sizing algorithm. In a simple layout with free space, 1fr and 2fr divide that space in a 1:2 ratio, subject to minimum sizes and other constraints.
4. repeat() and minmax()
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
Repeat avoids repeating the same track definition. minmax() defines a minimum and maximum sizing range.
.responsive-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px;
}Auto-fit and auto-fill can create responsive repeated tracks. Auto-fit collapses empty repeated tracks where appropriate, while auto-fill retains track slots even when they are empty.
5. Place Items by Grid Lines
.featured {
grid-column: 1 / 3;
}
.tall {
grid-row: 2 / 4;
}Grid line numbers define where an item starts and ends. A span keyword can also specify the number of tracks to cover.
6. Implicit Tracks
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(100px, auto);
}Items that require tracks not explicitly defined can create implicit tracks. Grid-auto-rows and grid-auto-columns control their sizing.