Sub topic 9
The implicit grid
This chapter assumes you can already declare a grid with grid-template-columns and grid-template-rows. It also assumes you know fr, repeat(), and placing items by line number.
Explicit and implicit tracks
The tracks you declare with grid-template-columns and grid-template-rows form the explicit grid. The browser creates any extra tracks on its own, and those form the implicit grid. This happens in two cases:
- There are more items than explicit cells, so the browser adds rows (or columns) to hold them.
- An item is placed on a line outside the explicit grid.
.list {
display: grid;
grid-template-columns: repeat(2, 1fr);
}Suppose this container has five children. Only columns are declared, so the browser creates three implicit rows. By default an implicit track is auto sized, which means it is as tall as its content.
Sizing implicit tracks
Use grid-auto-rows and grid-auto-columns to control the size of implicit tracks.
.list {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-auto-rows: minmax(100px, auto);
gap: 1rem;
}Every generated row is now at least 100px tall and grows when its content needs more space. If you give several values, they repeat as a pattern. grid-auto-rows: 80px 160px makes the generated rows alternate between 80px and 160px.
Implicit columns
Rows are generated by default because grid-auto-flow is row. Setting grid-auto-flow: column fills columns first, so the browser adds implicit columns when it runs out of rows.
.strip {
display: grid;
grid-template-rows: repeat(2, 80px);
grid-auto-flow: column;
grid-auto-columns: 150px;
}Placing an item outside the explicit grid also creates tracks:
.far {
grid-column: 5;
}If the container declares only three columns, this item lands in column 5. The browser creates implicit columns 4 and 5, and column 4 stays empty but takes up space.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Generated rows are different heights from your declared rows | `grid-auto-rows` defaults to `auto` | Set `grid-auto-rows` |
| `grid-column: 1 / -1` does not span a generated column | `-1` refers to the last line of the explicit grid only | Declare the columns you need, or use `span` |
| An unexpected empty track appears | An item was placed on a line beyond the explicit grid | Check the line numbers |
Exercise
A container sets grid-template-columns: repeat(3, 1fr) and has seven children. How many rows does the grid have, which of them are implicit, and what CSS makes each one at least 60px tall?
Show answer
Seven items in three columns need three rows. No rows are declared, so all three are implicit. Add grid-auto-rows: minmax(60px, auto); to make each row at least 60px tall while still growing to fit its content.