Flexbox Layout
Before flexbox, centering something vertically in CSS was notoriously difficult. Flexbox changed that. It's now the go-to tool for most one-dimensional layouts — navbars, card rows, button groups, and more.
Enabling Flexbox
Add display: flex to a container. Its direct children become flex items and are arranged in a row by default.
.container {
display: flex;
}
flex-direction
Controls whether items are laid out in a row or column:
.row {
display: flex;
flex-direction: row; /* default: left to right */
}
.column {
display: flex;
flex-direction: column; /* top to bottom */
}
Alignment
Two properties control alignment. Think of them as "main axis" and "cross axis":
justify-content— aligns items along the main axis (horizontal in a row)align-items— aligns items along the cross axis (vertical in a row)
.navbar {
display: flex;
justify-content: space-between; /* logo on left, links on right */
align-items: center; /* vertically centered */
}
Common values for justify-content:
justify-content: flex-start; /* pack to the start (default) */
justify-content: flex-end; /* pack to the end */
justify-content: center; /* center all items */
justify-content: space-between; /* first and last at edges, rest evenly spaced */
justify-content: space-around; /* equal space around each item */
Centering an Element
The classic flexbox trick — centering both horizontally and vertically:
.centered {
display: flex;
justify-content: center;
align-items: center;
}
This pattern works for centering a single child inside a container. It's one of the most-used snippets in CSS — worth memorizing.
flex-wrap
By default, flex items stay on one line even if they overflow. Use flex-wrap: wrap to let them wrap onto the next line:
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
gap
The gap property adds space between flex items without needing margins:
.buttons {
display: flex;
gap: 0.75rem;
}
flex on Items
The flex property on individual items controls how they grow and shrink:
.sidebar {
flex: 0 0 260px; /* don't grow, don't shrink, stay 260px */
}
.main {
flex: 1; /* take up all remaining space */
}
A Complete Example
.page-layout {
display: flex;
gap: 2rem;
align-items: flex-start;
}
.sidebar {
flex: 0 0 240px;
}
.content {
flex: 1;
min-width: 0; /* prevents overflow on long content */
}
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.