Sub topic 2
Placing Items in a CSS Grid
Assume you know basic HTML, CSS selectors, the box model, display, normal flow, and units such as px and rem. CSS Grid places items in rows and columns. A grid line is the boundary between tracks, where a track is a row or column.
Placing items by grid line
Lines are numbered from 1. A grid with three columns has four column lines. Use grid-column and grid-row to choose an item's start and end lines.
.grid {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: 120px 120px;
gap: 1rem;
}
.featured {
grid-column: 1 / 3;
grid-row: 1 / 3;
}The .featured item starts at column line 1 and ends before line 3, so it covers columns 1 and 2. It also covers rows 1 and 2.
Spanning rows and columns
You can express a span without calculating the ending line:
.card {
grid-column: 2 / span 2;
grid-row: 1 / span 2;
}This starts at column line 2 and covers two columns. Spanning is useful for featured cards and dashboard panels.
Naming areas with `grid-template-areas`
Named areas make page layouts easier to read. Each quoted row describes one grid row.
.layout {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }Every area must form a rectangle. A name cannot be split into separate regions.
The implicit grid
The explicit grid is the structure you define. If items need more rows or columns, Grid creates an implicit grid. Configure its tracks with grid-auto-rows or grid-auto-columns.
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 120px;
gap: 1rem;
}Auto-placement and `grid-auto-flow`
Items without placement rules are placed in available cells in document order. grid-auto-flow: column fills columns before starting new ones. The default is row.
.grid {
display: grid;
grid-auto-flow: row dense;
}dense fills earlier gaps when possible, but it can make the visual order differ from the source order.
Exercise
A grid has four columns. Which declaration makes an item cover columns 2 and 3?
Show answer
grid-column: 2 / span 2;