Flexbox (the Flexible Box layout) is the CSS layout model built for arranging items in a single row or column, handling spacing, alignment, and sizing automatically instead of relying on old hacks like floats. It's the single most useful layout tool in modern CSS — navbars, button groups, card rows, and centering content all commonly reach for flexbox first.

Flexbox works on a parent-child relationship: you turn a container into a "flex container," and every direct child inside it automatically becomes a "flex item" that the container can space out, resize, and align.

Turning On Flexbox

<div class="row">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
</div>
.row {
  display: flex;
}

Just adding display: flex to the parent is enough to change everything: the three boxes, which would normally stack as block-level divs, now sit side by side in a row automatically, each only as wide as its own content needs.

Main Axis vs Cross Axis

This is the single most important concept in flexbox. By default, the main axis runs horizontally (left to right) and the cross axis runs vertically (top to bottom) — but this depends entirely on flex-direction.

.row {
  display: flex;
  flex-direction: row;    /* default: main axis is horizontal */
}

.column {
  display: flex;
  flex-direction: column; /* main axis is now vertical */
}

With flex-direction: column, the main axis flips to vertical — the three boxes now stack top to bottom instead of side by side, and properties like justify-content, which always act along the main axis, now control vertical spacing instead of horizontal. Understanding which axis is "main" at any given moment is the key to not getting confused by flexbox's alignment properties.

A Simple Flex Row Layout

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
}

This produces a horizontal toolbar where every child is vertically centered relative to the tallest item (thanks to align-items: center, which works on the cross axis), with a consistent 12px gap between each item — no more manual margins on every child, and no leftover margin on the last item like the old float-based approach often left behind.

Where to Go Next

This guide covers the foundation; for the two properties you'll reach for constantly once a flex container is set up, see justify-content vs align-items explained, and for controlling how individual items grow or shrink to fill available space, see flex-grow, flex-shrink, and flex-basis.