CodePark/ questions / Grid
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Grid

When would you choose CSS Grid over Flexbox, and vice versa?

Choose Flexbox for one row or one column of items. Choose Grid when items must line up in rows and columns at the same time.

Flexbox is one-dimensional. It lays items out in a row or a column, and the content's size drives the layout. It suits:

  • navigation bars, toolbars and button groups
  • centring something
  • rows of items whose widths change with their content

Grid is two-dimensional. You define rows and columns, then place items into them, so items line up across both axes. Here the layout drives the content. It suits:

  • page layouts
  • card galleries
  • forms with aligned labels
  • anything where the layout should drive the content

Grid also offers named areas, explicit placement, overlapping items and subgrid. subgrid lets nested content align to the parent grid's tracks (its rows and columns).

They work well together. For example, use Grid for the page layout and Flexbox inside each component. Both support gap and the same alignment properties.

  • Flexbox works on one axis, and the content's size shapes the layout.
  • Grid works on two axes. You define the layout first, and the content fills it.
  • Grid adds named areas, explicit placement, overlap and subgrid.
  • The two are often combined, like a Grid page with Flexbox inside components.