Sub topic 14
Naming grid lines
This chapter assumes you can define tracks with grid-template-columns, place items with numbered lines, and use repeat() and fr. Numbered lines work, but they break when you add a column. Names make placement readable and stable.
Declaring line names
Put a name in square brackets between track sizes. Each name labels the grid line at that position.
.page {
display: grid;
grid-template-columns:
[full-start] 1fr
[content-start] minmax(0, 60rem)
[content-end] 1fr
[full-end];
}
.page > * {
grid-column: content;
}
.page > .banner {
grid-column: full;
}The four lines are named full-start, content-start, content-end and full-end. Writing grid-column: content is shorthand for content-start / content-end. The browser looks for a matching -start and -end pair. The .banner rule uses the same trick to stretch across the whole width.
Several names and repeated names
A line can have more than one name. Separate the names with spaces inside one pair of brackets, as in [content-end sidebar-start].
Several lines can also share a name. Then you select one by adding a number, which counts only lines with that name.
.cards {
display: grid;
grid-template-columns: repeat(3, [col] 1fr) [col-end];
}
.cards .wide {
grid-column: col 1 / col 3;
}repeat() stamps [col] before each of the three tracks. .wide runs from the first col line to the third, so it covers two columns. You can also use span col 2 for the same result.
Names from grid-template-areas
Areas create line names for you. An area called main produces the lines main-start and main-end in both directions. You can therefore mix approaches: place an item with grid-column: main-start / main-end even though you never wrote brackets.
The reverse also works. If you name lines x-start and x-end, an area called x exists, even when grid-template-areas does not mention it.
Common errors
- Quotes or commas in the brackets. A name is a bare identifier, so
["content-start"]is invalid and the whole declaration is dropped. - Typos. Names are case-sensitive. A name that matches no line does not produce an error. The item can fall into the implicit grid and add unexpected tracks.
- Reserved words.
spanandautocannot be line names. - Forgetting the pair.
grid-column: contentonly works when bothcontent-startandcontent-endexist. - Counting the wrong lines.
col 2means the second line namedcol, not the second line in the grid.
Exercise
Given grid-template-columns: [a] 100px [b] 1fr [c] 1fr [d];, which rule makes an item cover both 1fr columns, and why does grid-column: b-start / d fail to be necessary here?
Show answer
Use grid-column: b / d. The line names are a, b, c and d, so the item runs from line b to line d and covers the two 1fr tracks. The name b-start does not exist in this template, because the lines are named b, not b-start. A bare name such as b is used as a line name directly, and the -start/-end shorthand only applies when a matching pair exists.