Sub topic 18
Choosing between Flexbox and Grid
This chapter assumes you know display: flex, the main and cross axes, flex-wrap, and the flex shorthand from earlier chapters. You do not need prior Grid experience. The examples use only a few Grid properties.
The core difference
Flexbox lays out items along one axis at a time. Even with flex-wrap, each wrapped line is laid out on its own. Lines do not know about each other's item sizes.
CSS Grid defines rows and columns together. Items are placed into cells of a shared structure, so items in different rows line up in the same columns.
| Question | Flexbox | Grid |
|---|---|---|
| Dimensions controlled | One at a time | Rows and columns together |
| Sizing driven by | The content of the items | The layout you define on the container |
| Typical use | Components: navbars, toolbars, button groups | Page and section layouts, galleries |
| Wrapped lines align in columns | No | Yes |
Seeing the difference with wrapping
In the card example from earlier, flex: 1 1 200px lets each card grow to fill its line. If the last line has only one card, that card stretches across the full width. Each line shares out its own free space.
A Grid version keeps every card in the same column track:
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}Here the browser creates as many columns of at least 200px as fit. A last row with one card leaves the other columns empty instead of stretching that card.
A decision guide
Use Flexbox when:
- The items form a single row or column, such as a navbar or a toolbar.
- You want items to size themselves from their content and share leftover space.
- You need to push items apart with auto margins.
Use Grid when:
- You are building a two-dimensional structure, such as a header, sidebar, main area and footer.
- Items in different rows must share column widths.
- You want to define the layout on the container and place items into it.
Combining both
The two are not exclusive. A common structure uses Grid for the page and Flexbox inside each region:
.page {
display: grid;
grid-template-columns: 16rem 1fr;
min-height: 100vh;
}
.page .topbar {
display: flex;
justify-content: space-between;
align-items: center;
}.page is a Grid container, and .topbar is a Flexbox container nested inside one of its cells. Each container type only affects its own direct children.
Exercise
A product gallery wraps onto several rows. Every row must have the same column widths, and a last row with two products must not stretch them wider. Which layout system do you choose, and why?
Show answer
Grid. Rows and columns must share the same tracks, for example with grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)). Flexbox lays out each wrapped line separately, so the last line's items would grow with flex-grow or would not line up with the columns above.