CSS Flexbox
What is Flexbox?
Flexbox (Flexible Box) is a CSS layout model that makes it easy to arrange items in a row or column, align them, and distribute space. It solves most layout problems that used to require hacks with floats.
Enable Flexbox
CSS
.container { display: flex; /* makes this a flex container */ /* all direct children become flex items */ }
flex-direction — Main Axis
CSS
.container { display: flex; flex-direction: row; /* default: left to right → */ flex-direction: row-reverse; /* right to left ← */ flex-direction: column; /* top to bottom ↓ */ flex-direction: column-reverse; /* bottom to top ↑ */ }
justify-content — Alignment on Main Axis
CSS
.container { display: flex; justify-content: flex-start; /* [A B C ] */ justify-content: flex-end; /* [ A B C] */ justify-content: center; /* [ A B C ] */ justify-content: space-between; /* [A B C ] */ justify-content: space-around; /* [ A B C ] */ justify-content: space-evenly; /* [ A B C ] equal gaps */ }
align-items — Alignment on Cross Axis
CSS
.container { display: flex; height: 200px; align-items: stretch; /* default: items fill height */ align-items: flex-start; /* items at top */ align-items: flex-end; /* items at bottom */ align-items: center; /* items vertically centered */ align-items: baseline; /* aligned by text baseline */ }
Perfect Centering (Most Common Use)
CSS
.center-me { display: flex; justify-content: center; /* horizontal center */ align-items: center; /* vertical center */ min-height: 100vh; /* full viewport height */ }
flex-wrap and gap
CSS
.container { display: flex; flex-wrap: wrap; /* items wrap to next line if no room */ gap: 1rem; /* space between items (row and column) */ row-gap: 1rem; /* row gap only */ column-gap: 1.5rem; /* column gap only */ }
Flex Item Properties
CSS
.item { flex-grow: 1; /* grow to fill available space */ flex-shrink: 0; /* don't shrink below base size */ flex-basis: 200px; /* ideal starting size */ flex: 1 0 200px; /* shorthand: grow shrink basis */ align-self: center; /* override align-items for this item */ order: 2; /* change display order (default: 0) */ } /* Common pattern: equal-width columns */ .col { flex: 1; } /* each column gets equal space */
Real Example: Navigation Bar
CSS
nav { display: flex; justify-content: space-between; align-items: center; padding: 0 2rem; height: 64px; background: #1a1a2e; } .nav-links { display: flex; gap: 1rem; list-style: none; }