CSS Grid or Flexbox: how to choose for each layout
Flexbox lays items out in one direction, a row or a column. Grid lays items out in rows and columns at the same time. You will use both on almost every page, often one inside the other.
Use Flexbox when the content sets the size
A navigation bar has links of different widths. You want them in a row with even gaps and the last one pushed to the right. Flexbox handles that with display: flex, gap and margin-left: auto on the last item.
Use Grid when the layout sets the size
A dashboard has a sidebar of 240px and a content area that takes the rest. A product listing has cards that must line up in columns. Grid lets you define those tracks once with grid-template-columns and place content into them.
Five layouts and the tool for each
- Header with logo, menu and button: Flexbox.
- Card grid that wraps on small screens: Grid with repeat(auto-fill, minmax(260px, 1fr)).
- Page with sidebar and main area: Grid.
- Row of tags or chips: Flexbox with flex-wrap: wrap.
- Card with image, text and a button pinned to the bottom: Flexbox in a column, with margin-top: auto on the button.
Cards that line up inside
When cards in a row have titles of different lengths, their buttons end up at different heights. Grid's subgrid fixes this. Give the card grid-row: span 3 and grid-template-rows: subgrid, and the title, text and button rows align across all cards.
A quick test
Draw the layout on paper. If you drew lines in one direction, reach for Flexbox. If you drew a table of rows and columns, reach for Grid.