Sub topic 2
What Makes a CSS Grid Area Definition Valid
Assume you know basic CSS selectors, the box model, semantic HTML, media queries, and common length units. CSS Grid area definitions are strict: the browser accepts only rectangular regions with equally sized rows.
Valid and Invalid Area Definitions
Each quoted row in grid-template-areas represents one grid row. Each name represents one cell. A repeated name makes one area span multiple cells.
.page {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
.page > header { grid-area: header; }
.page > aside { grid-area: sidebar; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }Every row has two cells, and each named area forms a rectangle. An area cannot be split into separate regions or shaped like an L.
This definition is invalid because content is non-rectangular:
grid-template-areas:
"content content"
"content sidebar"
"footer footer";The content cells form an L shape. The browser ignores the declaration.
Repeating and Bounding Tracks
repeat() avoids writing the same track definition several times. minmax() sets a lower and upper bound for each track.
.cards {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 1rem;
}This creates three columns. Each column prefers to share available space through 1fr, but should not become narrower than 200px.
Responsive Columns with `auto-fit`
Use auto-fit when the number of cards should change with the container width.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr));
gap: 1rem;
}The browser creates as many columns of at least 200px as fit. auto-fit collapses unused columns, allowing existing cards to stretch. The inner min(100%, 200px) prevents a single column from overflowing a container narrower than 200px.
auto-fill keeps empty tracks. Choose it when the track structure should remain visible or stable. Choose auto-fit when content should fill the available row.
Exercise
Why is "main sidebar" / "main main" invalid as an area definition?
Show answer
The main cells form an L shape instead of one rectangle, so the browser rejects the declaration.