Sub topic 6
Placing items by grid line
This chapter assumes you can already create a grid container and define columns and rows with grid-template-columns and grid-template-rows. Here you place items by telling the browser which grid lines they start and end on.
What grid lines are
A grid line is the boundary between two tracks, or the outer edge of the grid. A grid with three columns has four vertical lines. A grid with three rows has four horizontal lines. Numbering starts at 1 on the left edge for columns and on the top edge for rows. This assumes a left-to-right language, because the numbering follows the writing direction.
Lines are also numbered from the end with negative numbers. -1 is the last line of the explicit grid, -2 is the one before it, and so on. Using -1 as an end line means "stretch to the right edge" without counting columns.
Placing an item
Each item has four placement properties: grid-column-start, grid-column-end, grid-row-start and grid-row-end. The item occupies the area between its start and end lines. The shorthands grid-column and grid-row take the start and end values separated by a slash.
<div class="grid">
<div class="a">A</div>
<div class="b">B</div>
<div class="c">C</div>
</div>.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 80px);
gap: 8px;
}
.a {
grid-column-start: 2;
grid-column-end: 4;
grid-row-start: 1;
grid-row-end: 2;
}
.b {
grid-column: 1 / 3;
grid-row: 2 / 4;
}
.c {
grid-column: 3 / -1;
grid-row: 2;
}Item A starts at column line 2 and ends at line 4, so it covers columns 2 and 3 in row 1. Item B covers columns 1 and 2 and rows 2 and 3. Item C starts at column line 3 and ends at -1, which is line 4, so it fills only column 3. It has a single row value, so it occupies row 2 only.
Rules to remember
- If you give only a start line, the item spans one track.
- Gaps do not change line numbers. The gap sits between tracks, inside the space between two lines.
- Items placed on the same cells overlap. The later item in the source order paints on top, and
z-indexcan change that. - Items you do not place are auto-placed into the remaining empty cells.
Line numbers are precise, but they are brittle. If you add a column, every -1 and every later number may need review. The next chapters show span and named areas, which handle those cases more safely.
Exercise
A grid has grid-template-columns: repeat(4, 1fr). Which columns does an item with grid-column: 2 / -1 cover?
Show answer
Four columns create five column lines, so -1 is line 5. The item runs from line 2 to line 5 and covers columns 2, 3 and 4.