CSS: flexbox vs grid — when do I use which?
poze 5 months ago66 gadeen
I can make most layouts with either one. Is there a rule for choosing?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
2 Repons
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.
Konekte pou di lòt moun si li te mache.
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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.