CSS Flexbox Tutorial: flex-direction, justify-content, align-items, flex-wrap, gap, flex-grow and Common Patterns
What Is Flexbox?
Flexbox lays out items in one direction (a row or a column) and handles spacing, alignment and sizing for you. Make a flex container, and its direct children become flex items.
css
.row {
display: flex;
gap: 1rem;
}
The Two Axes
- Main axis: the direction items flow (row by default, left to right)
- Cross axis: the other direction (up and down for a row)
Container Properties
| Property | What it does | Common values |
|---|---|---|
flex-direction | Sets the main axis | row, column, row-reverse |
justify-content | Aligns along the main axis | flex-start, center, space-between, space-around, flex-end |
align-items | Aligns along the cross axis | stretch, center, flex-start, flex-end |
flex-wrap | Let items move to a new line | nowrap, wrap |
gap | Space between items | 1rem |
Pattern 1: Navbar
css
.nav { display: flex; justify-content: space-between; align-items: center; padding: 1rem; }
.nav ul { display: flex; gap: 1.5rem; list-style: none; margin: 0; padding: 0; }
Pattern 2: Perfect Centering
css
.center { display: flex; justify-content: center; align-items: center; min-height: 100vh; }
Item Properties: flex-grow, shrink and basis
css
.f1 { flex: 1; } /* grow 1 */
.f2 { flex: 2; } /* grow 2 */
.f3 { width: 100px; } /* fixed */
.row { display: flex; width: 600px; gap: 10px; }
Measured in Chrome
item widths: 160, 320, 100
The container is 600px wide. The fixed item takes 100px and the two gaps take 20px. That leaves 480px, split in a 1 to 2 ratio: 160px and 320px.
| Property | Meaning |
|---|---|
flex-grow | How much extra space the item takes |
flex-shrink | How much it shrinks when space is short |
flex-basis | Starting size before growing or shrinking |
flex: 1 | Shorthand: grow 1, shrink 1, basis 0 |
align-self | One item's own cross axis alignment |
order | Change visual order. Do not use it to fix reading order |
Pattern 3: Sticky Footer
css
body { min-height: 100vh; display: flex; flex-direction: column; margin: 0; }
main { flex: 1; } /* takes all leftover height */
Pattern 4: Wrapping Cards
css
.cards { display: flex; flex-wrap: wrap; gap: 1rem; }
.cards > .card { flex: 1 1 15rem; } /* grow, shrink, start at 15rem */
Use gap Prefer
gap over margins between flex items. It is simpler and has no extra space at the ends.
Practice
- Build a navbar with the logo on the left and links on the right
- Center a card in the middle of the screen
- Make a row of three cards that wrap on small screens
Conclusion
Flexbox lines items up in one direction. Learn the main and cross axes, justify-content, align-items, gap and the flex shorthand.
Quick Summary: Flexbox idea; axes; container properties; navbar; centering; item sizing; sticky footer; cards.

