DEV3 Technologies home

DEV3 Developer Forum

CSS Grid or Flexbox: how do I decide which one to use?

dev3 ·

I use flexbox for everything, including full page layouts, and the nested wrappers are getting out of hand. When is Grid actually the better tool?

#css#grid#flexbox

0

1 reply

dev3 · Accepted answer

Rule of thumb

  • Flexbox is one-dimensional. It lays items along one axis (row or column) and lets content size drive the layout.
  • Grid is two-dimensional. You define rows and columns and place items into the grid; the layout drives the content size.

Use flexbox for

  • Navigation bars, toolbars, button groups.
  • Centering or aligning a few items in a line.
  • A component where the items decide their own width and should wrap or shrink (flex-wrap).
  • Pushing one item to the end: margin-left: auto.

Use grid for

  • Page shells: header, sidebar, main, footer.
  • Card galleries where rows and columns must line up.
  • Anything where items need to align across rows (forms with labels and inputs in two columns).
  • Overlapping items in the same cell.
.page {
  display: grid;
  grid-template-columns: 240px minmax(0, 1fr);
  grid-template-areas:
    "header header"
    "nav    main"
    "footer footer";
  min-height: 100dvh;
}
.page > header { grid-area: header; }
.page > nav    { grid-area: nav; }
.page > main   { grid-area: main; }
.page > footer { grid-area: footer; }

They combine well

A grid for the page, flexbox inside each cell. Subgrid (grid-template-columns: subgrid, supported in all current evergreen browsers) lets nested items align with the parent's tracks, which removes many wrapper hacks.

Test

If you find yourself setting fixed widths on flex children to make columns line up, you want grid. If you find yourself adding empty cells to make a grid behave, you want flex.

Try layouts visually with the CSS grid generator.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.