Flexbox Layout
What is Flexbox?
Flexbox (Flexible Box Layout) is a CSS layout mode designed for arranging items in one direction — either as a row or a column. Before flexbox, centering things and building responsive layouts required hacks. Flexbox makes it straightforward.
How to activate it
Add
display: flex to a container. All direct children become flex items:CSS
.container {
display: flex;
}HTML
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>By default, flex items sit side by side in a row.
Main axis vs cross axis
Flexbox always has two axes:
- Main axis — the direction items flow (default: horizontal).
- Cross axis — perpendicular to the main axis (default: vertical).
flex-direction:CSS
.container {
display: flex;
flex-direction: column; /* items stack vertically */
}Alignment
justify-content — aligns items along the main axis:CSS
.container {
display: flex;
justify-content: center; /* center items */
/* Other values: flex-start, flex-end, space-between, space-around, space-evenly */
}align-items — aligns items along the cross axis:CSS
.container {
display: flex;
align-items: center; /* vertically center items (in a row layout) */
}The classic centering trick
Centering something both horizontally and vertically used to be surprisingly hard. With flexbox:
CSS
.center-me {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}That's it. Three lines and you have a perfectly centered element.
Making items flexible
The
flex shorthand controls how items grow and shrink:CSS
.sidebar {
flex: 0 0 250px; /* don't grow, don't shrink, stay at 250px */
}
.main {
flex: 1; /* grow to fill remaining space */
}Wrapping
By default, flex items try to fit on one line. If you want them to wrap:
CSS
.container {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}gap adds space between items — much cleaner than using margins.Key takeaway
Flexbox is the go-to tool for one-dimensional layouts. Use
justify-content for the main axis, align-items for the cross axis, and gap for spacing. For two-dimensional layouts (rows and columns simultaneously), use CSS Grid instead.