What Flexbox is
Flexbox is a one-dimensional layout model that organizes items along a single axis (horizontal or vertical). It is the right tool when you have a group of elements you want to align, distribute or resize in a single direction: navbars, toolbars, lists, cards in a row.
Axes and properties
- flex-direction: defines the main axis. row (default) horizontal, column vertical.
- justify-content: aligns items on the main axis.
- align-items: aligns items on the cross axis.
- flex-wrap: lets items move to the next line if they overflow.
- gap: space between items.
Centering is one block
The "center vertically in CSS" meme died with flexbox. Today it is three lines:
display: flex;
justify-content: center;
align-items: center; Works in any container with a defined height (even 100vh). Goodbye to position: absolute and translate gymnastics.
flex shorthand
The flex property on each item controls how it grows, shrinks and its base size. Useful patterns:
- flex: 1: the item takes available space. Useful for equal columns.
- flex: 0 0 200px: fixed 200px, neither grows nor shrinks.
- flex: 1 0 200px: minimum 200px, grows if there is room.
- flex-shrink: 0: never shrinks even when space is tight.
Common patterns
Navbar with logo left and links right: justify-content: space-between. Form with label above and input below: flex-direction: column. Card with avatar + text: row with gap. Footer pushed to bottom: margin-top: auto on the last item pushes it down.
Common mistakes
- Confusing axes: switching flex-direction to column swaps the meaning of justify-content and align-items.
- flex: 1 by reflex: sometimes breaks overflow because it equalizes everything.
- Default min-width: by default flex items do not shrink below their content. Use
min-width: 0if you need text to truncate.
When not to use flexbox
If you need to control rows and columns at once (a product grid where each row has 3 items and you want cards to align vertically), Grid is the better tool. Flexbox shines on one axis; Grid on two.