CSS flexbox guide: the properties you need and nothing more
Flexbox solves one problem well: lay out items in a row or a column and share the space.
Container and items
Add display: flex to a parent and its direct children become flex items. Everything else is a property of the container or of an item. Only direct children are affected; grandchildren need their own flex container.
Container properties
flex-direction:row(the default),column, or the reversed forms. This sets the main axis.flex-wrap:nowrap(the default) keeps everything on one line, shrinking items if needed;wraplets items move to a new line.justify-content: space along the main axis.align-items: placing along the cross axis, for one line.align-content: placing of the lines when there are several.gap: space between the items.
Item properties
flex-grow: how much of the leftover space this item takes.1on every item shares it equally.0(the default) means no growing.flex-shrink: how much it shrinks when there is not enough room. The default of1lets items shrink.flex-basis: the starting size before growing or shrinking.autouses the item width.flex: 1is a shorthand for grow 1, shrink 1 and basis 0, the usual way to say "share the space".align-self: overridesalign-itemsfor one item.order: changes visual order. Screen readers and the Tab key still follow the HTML order, so use it carefully.
Recipes
A navigation bar: display: flex; justify-content: space-between; align-items: center; puts the logo at one end and the links at the other. A row of cards that wrap: display: flex; flex-wrap: wrap; gap: 16px; with flex: 1 1 240px on each card. A footer pushed to the bottom: make the page container display: flex; flex-direction: column; min-height: 100vh; and give the main content flex: 1.
Mistakes people make
- Text overflow: a flex item will not shrink below its content width unless you set
min-width: 0. This is why a long word or URL stretches a flex layout past the screen. - Images stretching. Items are stretched on the cross axis by default; set
align-items: flex-startor give the imagealign-self. - Using margins and
gaptogether and getting double spaces.
Is flexbox or grid better for page layout?
Both. Flexbox for components in one line, grid for areas with rows and columns. See the comparison page.
This is an independent site. It is not connected with the W3C, MDN, Google, Apple, Mozilla or Microsoft. Browser and product names belong to their owners.