Flexbox is CSS for one-dimensional layout: a row or a column of items that should share space, align, and wrap sensibly. Navigation bars, button groups, cards with a footer pinned to the bottom — these are all flexbox jobs, and they take a few lines once you know the four properties that matter.
Start with a container and a direction:
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
justify-content controls spacing along the main axis (the row), align-items controls the cross axis (vertical, for a row). space-between pushes the first item left and the last item right — the classic navbar pattern with no floats and no absolute positioning.
The real power is in how children grow and shrink. flex: 1 on a child means "take all the free space". A search input that fills the gap between a logo and a button is one declaration:
.search {
flex: 1;
}
And flex-wrap: wrap lets items drop to a new line on small screens instead of overflowing:
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
Centring — the thing that used to need three hacks — is now two lines:
.center {
display: flex;
align-items: center;
justify-content: center;
}
That centres a spinner, a login card, or an empty state both ways, whatever its size.
Three mistakes beginners make: first, setting fixed widths on flex children instead of letting flex-grow distribute space. Second, forgetting that gap works in flexbox in all modern browsers — no more margin hacks on every child except the last. Third, using flexbox for a full page grid — rows and columns together is Grid's job; flexbox is for a single row or column.
Ways to extend it: learn flex-shrink and flex-basis for finer control over how items share space, use align-self to override alignment for one child, and try order to rearrange items visually without touching the HTML. Flexbox plus Grid covers nearly every layout you will build.
Top comments (0)