Lesson 11: CSS Grid Basics
π² Lesson 11: CSS Grid Basics
CSS Grid is a powerful layout system for building 2D layouts with rows and columns. Unlike Flexbox, which works in one dimension at a time, Grid lets you work both horizontally and vertically, at once!
1. Creating a Grid Container
Start by defining a container and giving it display: grid. This activates the grid layout mode.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
grid-template-columnsβ defines how many columns and their widthrepeat(3, 1fr)β creates 3 equal-width columnsgapβ adds spacing between rows and columns
2. Placing Items in the Grid
By default, items auto-flow into the grid, but you can control exactly where each one goes with grid-column and grid-row.
.item {
grid-column: 2 / 4;
grid-row: 1 / 3;
}
This places the item starting from column 2 to 4, and row 1 to 3, effectively spanning 2 columns and 2 rows.
3. Grid Terminology
- Tracks: Rows and columns
- Gaps: Spacing between tracks
- Cells: The intersection of a row and a column
- Lines: Invisible lines separating rows/columns (used in placement)
β‘ Pro Tip
Grid is great for building cards, galleries, dashboards, and more. Combine it with media queries to build responsive layouts with ease.
β Recap
- Use
display: gridto enable Grid layout grid-template-columnsdefines column structuregapcreates spacing- Use
grid-columnandgrid-rowto control item placement
Now that you've got the grid basics down, the next level is using named areas, auto-placement, and responsive grids. Grid is magic. Own it.