CSS: flexbox vs grid — when do I use which?

asked 5 months ago68 viewsen

3

I can make most layouts with either one. Is there a rule for choosing?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

2 Answers

3
✓
✓ Accepted answer

A useful rule of thumb:

- Flexbox is one-dimensional: a row *or* a column. Content decides the sizing. Great for navbars, button groups, centering things, and a card's internal layout. - Grid is two-dimensional: rows *and* columns together. The layout decides the sizing. Great for page layouts, card galleries, dashboards, and forms with aligned labels.

/* responsive card gallery, no media queries */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 1rem;
}

/* navbar */
.nav { display: flex; align-items: center; gap: 1rem; }
.nav .spacer { margin-left: auto; }

They combine naturally: grid for the page skeleton, flex inside the components.

Sign in to tell others whether this worked.

answered 5 months ago
2

Also worth learning: subgrid is now supported in all major browsers. It lets nested elements (like card titles and footers) align across sibling cards, which used to be a classic reason to fight with flexbox.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.