Flexbox vs CSS Grid — when to use each?
Flexbox is one-dimensional (a row OR a column). Grid is two-dimensional (rows AND columns at once). Use flex for component layouts and toolbars, grid for page templates, dashboards, and any 2D alignment.
Both are modern layout systems; they're complementary, not competitors.
Flexbox lays out items along one axis at a time. You think in terms of: main axis vs cross axis, justify vs align, wrap vs nowrap. Perfect for:
- Toolbars and navbars (icons + spacing).
- Form rows.
- Vertical centering of one block.
- Component-level layouts where children flow in a single direction.
Grid lays out items in two dimensions simultaneously. You think in terms of: rows, columns, tracks, areas. Perfect for:
- Page templates (header / sidebar / main / footer with
grid-template-areas). - Dashboards with consistent gutters.
- Image galleries and product grids.
- Aligning items across both axes (which flex requires nesting to achieve).
Practical heuristic: if you find yourself nesting flex containers to align items in two dimensions, you wanted grid. If you find yourself fighting grid to handle dynamic-sized children, you wanted flex.
Combine them freely: page-level grid, component-level flex inside each grid cell.
Code
Follow-up questions
- •How do `auto-fit` and `auto-fill` differ in `repeat()`?
- •What does `subgrid` solve?
- •When does `flex: 1` produce different results than `flex: auto`?
Common mistakes
- •Using grid where flex would do — heavier mental model for one-dimensional cases.
- •Setting a child's `width` rigidly inside a flex container and breaking wrapping.
- •Forgetting `min-width: 0` on flex children that contain text — overflow ensues.
Performance considerations
- •Both are zero-cost layout primitives. Layout cost depends on tree depth and dynamic sizes.
Edge cases
- •`gap` works in both flex and grid — modern enough to drop margin hacks.
- •RTL: use logical alignment (`start` / `end`) instead of `left` / `right`.
Real-world examples
- •Most dashboard apps use grid for the shell and flex within each pane (toolbar, list rows).