Flexbox Basics
Turning a container into a flex layout and controlling the direction and wrapping of its children.
2 min read
Flexbox is a layout mode built for arranging items in a single row or column, handling the sizing and spacing between them without manual math. It's the tool you reach for before Grid whenever the layout is fundamentally one-dimensional — a navbar, a button group, a card's internal layout.
Turning on flex
.nav {
display: flex;
}<nav class="nav">
<a href="/">Home</a>
<a href="/docs">Docs</a>
<a href="/about">About</a>
</nav>Setting display: flex on a container makes its direct children flex items, laid out in a row by default, each sized to its content instead of stacking on separate lines the way block elements normally would.
Direction
.nav {
display: flex;
flex-direction: row; /* default: left to right */
}
.sidebar {
display: flex;
flex-direction: column; /* top to bottom */
}flex-direction sets the main axis. row lays items left-to-right, column lays them top-to-bottom. Every other Flexbox property (justify, align, gap) is defined relative to this main axis, so it's worth deciding direction first.
Spacing between items
.nav {
display: flex;
gap: 24px;
}gap puts consistent space between flex items without adding margin to each child individually — no more worrying about an extra margin on the last item that needs to be zeroed out. gap works the same way in Grid, covered later.
Wrapping
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}By default, flex items shrink to try to fit on one line, which can squash them uncomfortably if there are too many. flex-wrap: wrap lets items flow onto additional lines instead, which is essential for something like a list of tags where the count isn't known ahead of time.
Growing and shrinking individual items
.sidebar {
flex: 0 0 240px; /* don't grow, don't shrink, base width 240px */
}
.main {
flex: 1; /* grow to fill remaining space */
}<div style="display: flex;">
<aside class="sidebar">...</aside>
<main class="main">...</main>
</div>flex is shorthand for flex-grow, flex-shrink, and flex-basis. flex: 1 is one of the most common patterns in Flexbox — it tells an item to grow and consume any leftover space in the container, which is exactly how a "sidebar + fluid main content" layout is usually built: give the sidebar a fixed basis, and let the main area take flex: 1.