Sub topic 17
Putting it together: common layout patterns
This chapter combines the pieces from earlier chapters into three layouts you will build often. It assumes you know grid-template-columns, repeat(), minmax(), grid-template-areas, gap, and the difference between explicit and implicit tracks.
Pattern 1: The page shell
Named areas describe the page visually. The sidebar has a fixed width, and the main column takes the remaining space.
.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;
}
.layout > header { grid-area: header; }
.layout > aside { grid-area: sidebar; }
.layout > main { grid-area: main; }
.layout > footer { grid-area: footer; }The middle row uses 1fr, so it absorbs the leftover height. The footer stays at the bottom even when the content is short.
To make this layout responsive, redefine the areas in a media query:
@media (max-width: 600px) {
.layout {
grid-template-columns: 1fr;
grid-template-rows: auto auto 1fr auto;
grid-template-areas:
"header"
"sidebar"
"main"
"footer";
}
}The HTML source does not change. Only the grid definition does.
Pattern 2: The responsive card grid
When you do not know how many cards there will be, let the browser decide the column count.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
}Each column is at least 240px wide. The browser fits as many columns as it can, then stretches them to fill the row. No media queries are needed.
Pattern 3: The featured gallery
Spanning lets some items take more space. Dense packing fills the gaps they leave.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 120px;
grid-auto-flow: row dense;
gap: 8px;
}
.gallery .featured {
grid-column: span 2;
grid-row: span 2;
}grid-auto-rows sizes the rows that the implicit grid creates. A featured item covers a 2 by 2 block, and dense lets smaller items back-fill any holes.
Combining patterns
Real pages nest these patterns. The page shell is a grid, and the main area can contain a card grid. Where one dimension is enough, such as a row of buttons inside a card, use Flexbox. A common rule is to use Grid for the overall structure and Flexbox for the content inside each piece.
Choosing a pattern
| Need | Pattern |
|---|---|
| Header, sidebar, content, footer | Named areas |
| Unknown number of equal items | `auto-fit` with `minmax()` |
| Some items larger than others | Spans with `grid-auto-rows` |
Exercise
A card grid uses repeat(auto-fit, minmax(240px, 1fr)). The container is 1000px wide with a 24px gap. How many columns does it have?
Show answer
Four. Four 240px columns plus three 24px gaps need 960 + 72 = 1032px, which does not fit in 1000px. Three columns need 720 + 48 = 768px, which fits. So the browser creates three columns and stretches each to about 317px. The answer is three, not four.