Flexbox Fundamentals
Flexbox is a one-dimensional layout system for distributing space along a single axis (row or column). It replaced the old float-based layouts and solves problems like vertical centering, equal-height columns, and flexible spacing — things that were notoriously difficult before Flexbox.
40 min•By Priygop Team•Last updated: Feb 2026
Flex Container Properties
- display: flex — Turns an element into a flex container. Direct children become flex items
- flex-direction — row (default, horizontal), column (vertical), row-reverse, column-reverse
- justify-content — Distributes space along main axis: flex-start, center, flex-end, space-between, space-around, space-evenly
- align-items — Aligns items along cross axis: stretch (default), center, flex-start, flex-end, baseline
- flex-wrap — nowrap (default, items shrink), wrap (items flow to next line), wrap-reverse
- gap — Space between items: gap: 16px or row-gap: 16px column-gap: 24px. Replaces margin hacks
Flex Item Properties
- flex-grow — How much an item grows relative to siblings. flex-grow: 1 means fill available space equally
- flex-shrink — How much an item shrinks when container is too small. Default is 1 (shrink equally)
- flex-basis — Initial size before growing/shrinking. Similar to width but respects flex algorithm
- flex — Shorthand: flex: 1 = flex-grow: 1, flex-shrink: 1, flex-basis: 0%. Use this instead of individual properties
- align-self — Override align-items for a single item: align-self: center on one child
- order — Change visual order without changing HTML. Default is 0. Negative values move items earlier
Flexbox Code Examples
Example
/* Centering anything — the classic Flexbox solve */
.center-both {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
min-height: 100vh;
}
/* Navigation bar */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
}
.navbar .nav-links {
display: flex;
gap: 24px;
}
/* Card layout with equal heights */
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 300px; /* grow, shrink, min-width 300px */
/* All cards stretch to equal height automatically! */
}
/* Sticky footer layout */
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.page main { flex: 1; } /* Main content fills remaining space */
.page footer { /* Footer stays at bottom */ }
/* Holy grail layout */
.holy-grail {
display: flex;
}
.holy-grail .sidebar { flex: 0 0 250px; } /* Fixed width */
.holy-grail .content { flex: 1; } /* Fill remaining */
.holy-grail .aside { flex: 0 0 200px; } /* Fixed width */Try It Yourself: Flexbox Playground
Try It Yourself: Flexbox PlaygroundHTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|36 lines|1924 chars|✓ Valid syntax
UTF-8