Flexbox, short for the CSS Flexible Box Layout, is a way of telling a browser to line up a set of items in one direction, either a row or a column, and decide how they share the space. It is the standard tool for things like navigation bars, button groups and centring content, jobs that used to need fragile tricks.
How a flex container arranges items
You set display: flex on a parent element. Its direct children become flex items laid out along the main axis, which is horizontal by default or vertical with flex-direction: column. Two properties do most of the work: justify-content distributes items along the main axis (start, centre, space-between and so on), and align-items aligns them on the cross axis. gap adds even spacing between them.
Each item can grow, shrink or hold a base size through flex-grow, flex-shrink and flex-basis, usually written together as flex: 1. With flex-wrap: wrap, items that run out of room move onto a new line, which gives a simple responsive behaviour without any media queries.
An example: a plumber's header bar
A header holds a logo, three menu links and a "Call now" button. With display: flex; justify-content: space-between; align-items: center; the logo sits left, the button right, the links in between, all vertically centred regardless of the logo's height. On a narrow phone, a media query can switch the links into a hidden navigation menu while keeping the same flex row for logo and button.
Flexbox or Grid?
Flexbox is one-dimensional: it thinks about a single row or column, letting content size drive the layout. CSS Grid is two-dimensional, defining rows and columns together. A practical rule: use flexbox for components (a toolbar, a card's footer, a list of tags) and Grid for page-level structure or anything that must line up in both directions. They combine well, often a grid of cards whose insides use flexbox.
For an owner, flexbox is behind much of what makes a site hold together on different screens. Layout bugs like a button dropping onto its own line or text squashing into a narrow column are often flexbox settings.
Common flexbox mistakes
- Expecting children of children to flex. Only direct children of the container are flex items.
- Text overflowing a flex item. Items default to
min-width: auto, so long words or URLs can push past the edge until you setmin-width: 0. - Faking a grid with wrapped flex rows. The last row's items stretch or misalign; Grid handles that case cleanly.
- Using
orderto rearrange content, which changes the visual order but not the keyboard or screen-reader order.
Related terms
- CSS Grid: the two-dimensional layout counterpart.
- CSS: the language flexbox belongs to.
- Responsive design: a goal flex wrapping helps with.
- Navigation bar: a classic flexbox layout.