Flexbox and Grid solve overlapping problems, which is why people keep asking which one to learn. The honest answer: both, because they're built for different shapes of layout.
Flexbox lays elements out along a single axis — a row or a column — and excels at distributing space between items in that one direction.
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
justify-content controls spacing along the main axis, align-items controls alignment on the cross axis. A navbar with a logo on the left and links on the right is a two-line solution with Flexbox.
Grid defines rows and columns simultaneously, and lets you place items into specific cells — something Flexbox structurally cannot do on its own.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
repeat(3, 1fr) creates three equal-width columns; gap replaces the old margin-hacking approach to spacing between cells.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 20px;
}
auto-fit with minmax is the pattern worth memorizing: it fits as many 240px-minimum columns as will comfortably fit, and reflows automatically at any screen width — no media query required.
.center {
display: flex;
justify-content: center;
align-items: center;
}
Two lines, works for text or a whole child element, no table hacks or negative margins. This one snippet alone is worth learning Flexbox for.
Comments