Flexbox
~310 words ยท 2 min read
Flexbox: one-dimensional layout
Flexbox lays items along a single line โ either a row or a column. It's the go-to tool for nav bars, button groups, card rows, and centring content. Apply display: flex to a parent and its direct children become flex items.
The two axes
Every flex container has a main axis (the direction items flow) and a cross axis (perpendicular to it). flex-direction sets the main axis:
.container {
display: flex;
flex-direction: row; /* default: left to right */
/* flex-direction: column; top to bottom */
}
Alignment
Two properties control distribution:
- justify-content โ alignment along the main axis (
flex-start,center,space-between,space-around). - align-items โ alignment along the cross axis (
stretch,center,flex-start).
.container {
justify-content: center; /* main axis */
align-items: center; /* cross axis โ perfect centring */
}
Sizing items
Three properties control how items grow, shrink, and size:
- flex-grow โ how much extra space an item absorbs (0 = don't grow).
- flex-shrink โ how much it shrinks when space is tight.
- flex-basis โ the starting size before growing/shrinking.
The shorthand flex: 1 means grow equally; flex: 0 0 200px means fixed at 200px.
Gap
Modern flex supports gap for spacing between items โ no more margin hacks:
.container { display: flex; gap: 1rem; }
Confused about which alignment property to use?justify-contentfollows the main axis (the flex-direction);align-itemsfollows the cross axis. Flip the direction and they swap roles.