Sub topic 18
Choosing between Flexbox and Grid
This chapter assumes you know the Flexbox properties from earlier chapters: display: flex, the main and cross axes, flex-wrap, gap, and the flex shorthand. You should also know basic CSS selectors and the box model. It does not teach Grid in full. It gives you the criteria for deciding which tool fits a layout, and shows how to use both together.
The core difference
Flexbox is one-dimensional. It lays items out along a single axis. With flex-wrap, it breaks the items into several lines, but each line is laid out on its own. A line does not know what the line above it is doing.
Grid is two-dimensional. You define rows and columns on the container, and items are placed into the cells those tracks create. Every row sees the same columns, so items line up in both directions.
A second difference is where sizing decisions start:
- Flexbox works from the content out. The items' sizes (
flex-basis, content width) determine how much space each takes. The container then distributes leftover space or removes overflow. - Grid works from the layout in. The container's track definitions determine the space. Items are fitted into the tracks.
Most decisions follow from this. If the content should drive the layout, use Flexbox. If a defined structure should drive the layout, use Grid.
A decision flow
Apply the flow to one container at a time, not to the whole page. A single page normally contains both.
Where Flexbox fits better
Use Flexbox when the layout is a flow of items, and the number or width of items is unknown.
- Navigation bars and toolbars. The items are a row of varying widths, and auto margins can push groups apart.
- Centering one child.
justify-contentandalign-itemsdo this with little code. - Components with a flexible middle. A media object has an avatar, a text block that grows, and a button. Only one axis matters.
- Sticky footers. A column container with
flex: 1onmainis simple and reliable. - Tag lists and button groups. Items wrap naturally, and it does not matter that the last line is ragged.
Where Grid fits better
Use Grid when items must line up across rows and columns, or when you want to name regions of the page.
- Page layouts with header, sidebar, content, and footer.
- Card galleries where every card must share column edges with the cards above it.
- Forms with labels in one column and inputs in another.
- Overlap, where items share cells deliberately.
The wrapping problem
The clearest case where Flexbox falls short is a wrapped card list. Each flex line distributes its own free space, so the last line behaves differently from the others.
.cards {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.card {
flex: 1 1 200px;
}With ten cards, a full line might hold four cards. The last line holds two. Because flex-grow is 1, those two stretch to fill the whole line, so they end up much wider than the other cards. Removing flex-grow fixes the width but leaves the last line left-aligned with a gap at the end. Neither result is a true column alignment.
Grid solves this by defining the columns once:
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}Here auto-fill creates as many columns of at least 200px as fit. 1fr lets the columns share the space equally. Every card sits in a column track, so the last row uses the same column widths as the others, and the leftover cells stay empty.
The cost is that Grid's tracks are rigid: an item cannot grow larger than its track because the content wants more room.
Using both together
The question is rarely "Flexbox or Grid for the page". Grid usually lays out the large regions, and Flexbox arranges the contents inside each region. The two can nest freely.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Grid page with a Flexbox header</title>
<style>
body {
display: grid;
grid-template-columns: 12rem 1fr;
grid-template-areas:
"header header"
"nav main"
"footer footer";
grid-template-rows: auto 1fr auto;
min-height: 100vh;
margin: 0;
}
header {
grid-area: header;
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem 1rem;
background: #eef;
}
header .login {
margin-left: auto;
}
nav { grid-area: nav; }
main { grid-area: main; }
footer { grid-area: footer; }
</style>
</head>
<body>
<header>
<strong>Site</strong>
<a href="#">Docs</a>
<a class="login" href="#">Log in</a>
</header>
<nav>Menu</nav>
<main>Content</main>
<footer>Footer</footer>
</body>
</html>Grid defines the page's four regions and keeps the footer at the bottom through the 1fr row. Flexbox arranges the header's items in a row and pushes the login link to the end with an auto margin. Each tool handles the job it suits.
Gotchas when mixing them
- Properties that look alike do not always behave alike.
justify-contentandalign-itemsexist in both modules. In Flexbox they refer to the main and cross axes. In Grid they refer to the inline and block axes, andjustify-itemsalso exists. The axis rule from the Flexbox chapters does not transfer directly. gapworks in both. You can usually move a layout from one to the other without rewriting spacing.orderhas the same accessibility cost in both. It changes the visual order but not the keyboard or screen-reader order. Grid's explicit placement (grid-area,grid-column) has the same problem. Keep the source order meaningful.- Grid items have an automatic minimum size, too. A
1frtrack behaves likeminmax(auto, 1fr), so long unbreakable content can stretch it. The fix isminmax(0, 1fr), the Grid counterpart ofmin-width: 0. - Do not fake a grid with percentage widths on flex items. Matching columns with
flex-basis: 33.33%plus gap math breaks as soon as the gap changes. If you are calculating widths by hand to line items up, switch to Grid.
Quick comparison
| Question | Flexbox | Grid |
|---|---|---|
| Dimensions controlled | One axis per line | Rows and columns together |
| Sizing starts from | Item content and `flex` values | Track definitions on the container |
| Items in different lines align | No | Yes |
| Best for | Components, toolbars, centering | Page layouts, galleries, forms |
| Overlapping items | Awkward | Natural |
When both work
Some layouts are fine in either. A simple row of three equal columns works with flex: 1 on each item, or with grid-template-columns: repeat(3, 1fr). In that case, pick the one that matches how you think about the layout. If you think "three columns", use Grid. If you think "a row of things", use Flexbox. Both are well supported in current browsers, so support is not a reason to choose.
Exercise
A product page shows a list of tags (such as "new", "sale", "limited") of varying widths under a title. The tags should sit in a row and wrap to a new line when there is no room. A separate section below shows 12 product cards that must keep the same column edges on every row, including a last row that has only 2 cards. Which layout module fits each part, and why?
Show answer
Use Flexbox for the tags: their widths vary, no column alignment is needed, and a ragged last line is acceptable, so display: flex; flex-wrap: wrap; gap: 0.5rem is enough. Use Grid for the cards: they must share column edges across rows, and the last row must not stretch. Define columns with grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)) so every row uses the same tracks.
Exercise
A grid column declared as 1fr is stretched wider than expected by a long unbroken URL inside one of its items. What is the cause, and which declaration fixes it?
Show answer
A 1fr track has an automatic minimum size based on its content, so the long URL prevents the track from shrinking. Declare the track as minmax(0, 1fr) so the minimum becomes zero. This is the Grid counterpart of setting min-width: 0 on a flex item.