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

posée 5 months ago71 vuesen

3

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 5 months ago

2 réponses

3
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

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.

Connectez-vous pour dire si ça a marché.

answered 5 months ago

Sign in and verify your email to post an answer.