CSS Flexible Box Layout (Flexbox) is a one-dimensional layout algorithm designed to distribute space and align items along a primary axis. It automatically adapts to variable screen dimensions and dynamic content sizes.
The Two Axes of Flexbox
Every flex layout is defined by two perpendicular axes:
flex-direction: row (Default)
Main Axis: ============================> (Inline / Horizontal)
Cross Axis: ||
|| (Block / Vertical)
\/
flex-direction: column
Main Axis: || (Block / Vertical)
Cross Axis: ============================> (Inline / Horizontal)
- Main Axis: Established by
flex-direction(row,row-reverse,column,column-reverse). - Cross Axis: Runs perpendicular to the Main Axis.
The Complete Alignment Property Matrix
| Property | Governs Which Axis? | Applied To? | Key Values |
|---|---|---|---|
justify-content | Main Axis | Container | flex-start, flex-end, center, space-between, space-around, space-evenly |
align-items | Cross Axis (Single line) | Container | stretch (default), center, flex-start, flex-end, baseline |
align-content | Cross Axis (Multi-line) | Container | stretch, center, space-between, space-around (Active only when flex-wrap: wrap creates multiple lines) |
align-self | Cross Axis (Single item) | Item | Overrides the container's align-items for one specific child element |
.flex-parent {
display: flex;
flex-direction: row;
justify-content: space-between; /* Items pushed to opposite edges */
align-items: center; /* Centered vertically along cross axis */
flex-wrap: wrap; /* Wraps onto next row if container runs out of room */
gap: 1.5rem; /* Spacing between items without margin resets */
}
The Centering Holy Grail
Before Flexbox, centering an element both horizontally and vertically required complex positioning hacks or table simulations. With Flexbox, it is two lines:
.perfect-center {
display: flex;
justify-content: center; /* Main axis center */
align-items: center; /* Cross axis center */
min-height: 100vh;
}
The Power of margin: auto in Flexbox
In Flexbox, applying margin: auto (or margin-left: auto) to a flex child absorbs all remaining available free space on the main axis. This eliminates the need for empty spacer divs in navigation headers:
.navbar {
display: flex;
align-items: center;
}
.logo {
font-weight: bold;
}
/* Pushes all subsequent nav items to the far right! */
.nav-menu {
margin-inline-start: auto;
}
Exercises
- Build a card header with a title on the left and an action button pushed to the far right using
margin-inline-start: auto. - Demonstrate how
align-items: baselinealigns elements with differing font sizes along their typographic baseline. - Compare
space-between,space-around, andspace-evenlyusing a 3-item flex container.