Sub topic 9
Laying out the page with grid and flexbox
This chapter assumes you know basic HTML tags and attributes, basic CSS selectors and properties, and how to open a page in a browser and inspect it with developer tools. You should also have the semantic skeleton from the earlier chapters: header, main, and footer as direct children of body, with the hero as the first section inside main.
The working model: two tools, two jobs
CSS grid and flexbox both arrange child elements inside a parent, but they answer different questions.
- Grid is two-dimensional. You describe rows and columns, and the browser places items into that structure. Use it when the page or component has an overall shape.
- Flexbox is one-dimensional. It lays items along a single axis (a row or a column) and distributes the free space along it. Use it when you have a line of things to align, such as navigation links.
A page uses both. Grid places the big regions (header, main, footer). Flexbox arranges the contents inside a region.
| Question | Better fit |
|---|---|
| Where do the header, main, and footer sit vertically? | Grid |
| How do the logo and nav links line up in one row? | Flexbox |
| How do cards fill a row and wrap to the next one? | Grid |
| How do I center one item along an axis? | Flexbox |
Both tools work on a container (the parent that has display: grid or display: flex) and its items (the direct children only). Grandchildren are not affected. This is the most common source of "my layout does nothing" bugs: the rule was applied to the wrong element.
Keeping the footer at the bottom
On a short page, such as a "Thanks for your order" screen, the content may not fill the window. Without help, the footer rides up under the content and leaves empty space below it. The fix is to make the body a grid with three rows.
body {
margin: 0;
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
}Each part of this rule matters:
min-height: 100vhmakes the body at least as tall as the viewport.vhis one percent of the viewport height. Usingmin-heightinstead ofheightlets the body grow past the window when content is long.grid-template-rows: auto 1fr autodefines three rows.autosizes a row to its content.1fris one fraction of the leftover space, so the middle row absorbs all remaining height.- The three direct children of
bodyfill the three rows in source order:header,main,footer.
The grid works because the HTML puts exactly three children in body. If you add a fourth direct child, such as a cookie banner, it falls into an implicit fourth row and the footer no longer sits in the last auto row. Keep extra elements inside one of the three regions, or take them out of the flow with position: fixed.
Why not just use flexbox on the body?
You can. display: flex; flex-direction: column; min-height: 100vh; on body, plus flex: 1 on main, gives the same result. Grid is slightly more direct here because the three-row structure is stated in one line. Either is acceptable. Choose one and use it consistently in a project.
Arranging the header with flexbox
The header holds the site name and the navigation. They should sit on one row, with the name at the left and the links at the right.
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
header nav ul {
display: flex;
gap: 1.5rem;
list-style: none;
margin: 0;
padding: 0;
}Flexbox has a main axis and a cross axis. With the default flex-direction: row, the main axis runs horizontally and the cross axis runs vertically. Two properties control alignment:
justify-contentdistributes items along the main axis.space-betweenpushes the first item to the start and the last to the end.align-itemsaligns items along the cross axis.centercenters them vertically.
If you switch to flex-direction: column, the axes swap. justify-content then works vertically. Many alignment bugs come from forgetting this swap.
The header has two direct children, the logo link and the nav, so space-between splits them to the two edges. The second rule makes a flex container of the ul, which turns its li items into a row. gap adds space between items without needing margins on each one. The list-style, margin, and padding resets remove the bullets and default indentation of the list.
The semantics do not change when you restyle the list. A ul with display: flex is still a list, and screen readers still announce it as one in most browsers. (Safari with VoiceOver historically dropped list semantics when list-style: none was applied. If that matters for your audience, add role="list" to the ul.)
When the header gets too crowded
By default, flex items do not wrap. If the logo and links are wider than the container, they overflow or shrink. You have two options:
- Add
flex-wrap: wrapto the header so items drop to a second line when needed. - Collapse the links behind a menu button on narrow screens. That is a larger pattern and is covered in the responsive chapter.
Laying out the hero with grid
The hero has two children: a text block and an image. A grid with a column count that changes at a breakpoint handles it.
.hero {
display: grid;
gap: 2rem;
padding: 3rem 1.5rem;
}
.hero img {
max-width: 100%;
height: auto;
}
@media (min-width: 48rem) {
.hero {
grid-template-columns: 1fr 1fr;
align-items: center;
}
}Read it from top to bottom:
- With no
grid-template-columns, the grid has one column, so the text and image stack. This is the narrow-screen layout and the default. max-width: 100%stops the image from overflowing its cell.height: autokeeps the proportions.- At 48rem (768px at the default font size) and wider, the hero becomes two equal columns.
align-items: centercenters each child vertically in its row.
This is a mobile-first approach: the base rules describe the small layout, and min-width media queries add complexity as space allows. Rules that only apply on large screens stay in one place, and small devices do not have to undo anything.
The fr unit is a fraction of the free space in the grid container. 1fr 1fr gives two equal columns. 2fr 1fr would make the first twice as wide as the second. One gotcha: an fr track will not shrink below the minimum content size of its items. A long unbroken string, or an image without max-width: 100%, can force a column wider than you expect. If a column refuses to shrink, try minmax(0, 1fr) in place of 1fr.
A card grid without media queries
For the content sections, a row of cards often needs to show three across on a wide screen and one on a phone. You can get that behavior from a single declaration.
.card-grid {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
}minmax(16rem, 1fr) says each column is at least 16rem and at most one equal share of the space. repeat(auto-fit, ...) tells the browser to create as many such columns as fit in the container. On a container of 50rem, three columns fit and each grows to roughly 16.7rem. On a phone 20rem wide, only one fits, and it takes the full width.
auto-fit and auto-fill look similar. When there are fewer items than columns, auto-fill keeps the empty columns, so items stay at their minimum size. auto-fit collapses empty columns, so the items stretch to fill the row. For cards, auto-fit is usually what you want.
A caution: if the container is narrower than 16rem, the single column overflows. For small viewports with side padding, you can guard against this with minmax(min(16rem, 100%), 1fr).
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Footer floats mid-screen on short pages | No `min-height` on `body`, or the grid rows are not set | Use `min-height: 100vh` and `grid-template-rows: auto 1fr auto` |
| Footer is not in the last row | A fourth direct child of `body` | Move the extra element inside a region, or use `position: fixed` |
| `justify-content` does nothing | The element is not a flex container, or the free space is zero | Set `display: flex` on the parent and check its width |
| Items do not line up vertically | Wrong axis in mind after `flex-direction: column` | Remember `align-items` is the cross axis |
| Image overflows its grid cell | No `max-width: 100%` | Add `max-width: 100%; height: auto` |
| Page scrolls sideways | Fixed widths or a `minmax` minimum wider than the screen | Use relative units and `min()` inside `minmax` |
| Layout is on the wrong elements | Rule applied to a grandchild, not a direct child | Apply `display` to the direct parent |
Diagnosing with developer tools
Both Chrome and Firefox show a small "grid" or "flex" badge next to an element in the Elements (or Inspector) panel. Click it to draw an overlay showing tracks, gaps, and item boundaries. This is the fastest way to see whether your rule landed on the right element and how the browser sized each track.
How the pieces nest
The page uses grid at the top level, flexbox inside the header, and grid again inside the hero and the card section.
The tools nest because each container only controls its direct children. The body grid does not know about the nav links, and the nav flex container does not know about the footer. That separation keeps each rule short and easy to change.
Summary of the decisions
- Make
bodya three-row grid so the footer stays at the bottom of short pages. - Use flexbox for single-line groups such as the header and the navigation list.
- Use grid for the hero's two columns and for card collections.
- Start with the narrow layout and add
min-widthmedia queries for wider screens. - Check the result with the grid and flex overlays in developer tools.
Exercise
A page's body has display: grid; grid-template-rows: auto 1fr auto; min-height: 100vh. A developer adds a cookie banner as a new div placed after the footer and as a direct child of body, with no special positioning. The footer now sits in the middle row's place and the banner is at the bottom of the grid. Explain why this happens, and give two ways to fix it.
Show answer
The grid has three explicit rows, and the four direct children fill them in source order. So header takes the first auto row, main takes the 1fr row, and footer takes the last auto row. The banner is the fourth child, so it goes into an implicit fourth row, which gets only the size of its content. As a result the footer is no longer the last item and the banner appears below it. Fix 1: give the banner position: fixed (for example, bottom: 0), which removes it from the grid flow so it does not take a row. Fix 2: move the banner inside one of the three regions, such as inside footer, so body has exactly three direct children again.
Exercise
You want a grid of product cards that shows as many columns as fit, with each column at least 14rem wide, and with the cards stretching to fill the row when there are only two cards in a wide container. Write the grid-template-columns declaration and say which keyword you chose between auto-fit and auto-fill, and why.
Show answer
grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));. With auto-fit, empty columns collapse to zero width, so the two cards expand to share the whole row. With auto-fill, the empty columns would still be reserved, and the two cards would stay near their minimum width and leave blank space on the right.
Exercise
In a header with display: flex; flex-direction: column; align-items: center;, which axis does align-items control, and in which direction does the content get centered?
Show answer
With flex-direction: column, the main axis is vertical and the cross axis is horizontal. align-items controls the cross axis, so the items are centered horizontally within the header. justify-content would control the vertical distribution.