Flex Container
Flexbox Container
A Flexbox layout starts by making a container a flex container. Set display: flex (or display: inline-flex) on a parent element. The direct children become flex items.
.container {
display: flex;
}
inline-flex makes the container behave like an inline element (it only takes as much width as needed):
.container-inline {
display: inline-flex;
}
Common container properties you will use a lot:
flex-direction– row / column directionflex-wrap– wrap items to multiple linesgap– spacing between itemsjustify-content– align on the main axisalign-items– align on the cross axis
Direction and wrapping:
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 12px;
}
Tip: flex-direction changes the main axis. That also changes how justify-content and align-items behave.
Flexbox Justify Content
justify-content aligns items along the main axis (row by default).
Common values:
flex-start– pack items at the startcenter– center itemsflex-end– pack items at the endspace-between– first at start, last at end, space betweenspace-around– equal space around itemsspace-evenly– equal space between items (and edges)
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
If you switch to flex-direction: column, justify-content aligns vertically:
.sidebar {
display: flex;
flex-direction: column;
justify-content: center; /* vertical centering now */
}
Flexbox Align Items
align-items aligns items along the cross axis (vertical by default in a row).
Common values:
stretch– stretch items to fill the cross axis (default)flex-start– align to the startcenter– align to the centerflex-end– align to the endbaseline– align text baselines
.row {
display: flex;
align-items: center;
gap: 10px;
}
Baseline example (useful for mixed font sizes):
.row {
display: flex;
align-items: baseline;
gap: 10px;
}
Tip: For multi-line flex layouts (with wrapping), use align-content to control how lines are spaced. align-items aligns items within each line.
Summary
- Make a flex container with
display: flexorinline-flex. justify-contentaligns items on the main axis.align-itemsaligns items on the cross axis.- Main axis changes when you switch
flex-direction.