Flexbox Alignment & Ordering
Flexbox's real power shows in how easily it aligns and distributes items — problems that were notoriously painful with older CSS layout techniques.
.container {
display: flex;
justify-content: center; /* alignment along the main axis (row by default) */
align-items: center; /* alignment along the cross axis */
flex-wrap: wrap; /* allow items to wrap onto multiple lines */
}
justify-content aligns items along the main axis (horizontal, for the default row direction):
flex-start(default) — items packed at the start.center— items packed toward the center.space-between— first and last items touch the edges, remaining space distributed evenly between items.space-around— equal space around every item, including the outer edges.
align-items aligns items along the cross axis (vertical, for a row):
stretch(default) — items stretch to fill the container's height.center— items centered vertically.flex-start/flex-end— items aligned to the top or bottom.
A single-declaration trick many developers rely on to perfectly center anything:
.center-everything {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
This two-line combination (justify-content + align-items, both center) reliably centers content both horizontally and vertically — a problem that required several fragile workarounds before Flexbox existed.
Reordering without touching HTML:
.item-priority { order: -1; } /* moves this item before its siblings visually */
order changes the visual order of flex items independently of their order in the HTML source — useful for reordering content on different screen sizes without duplicating markup, though it should be used carefully since it can create a mismatch between visual order and keyboard/screen-reader tab order.