What is Flexbox?
Flexbox is a CSS layout method that makes it easy to arrange items in a row or column, align them, and distribute space. Before Flexbox, simple things like centering something vertically required complex hacks.
Enabling Flexbox
Set display: flex on a container. All its direct children become flex items:
<div class="navbar"> <!-- flex container -->
<a href="/">Logo</a> <!-- flex item -->
<nav>...</nav> <!-- flex item -->
<button>Sign In</button> <!-- flex item -->
</div>
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 32px;
}
flex-direction — Row or Column?
.container {
display: flex;
flex-direction: row; /* left to right (default) */
flex-direction: row-reverse; /* right to left */
flex-direction: column; /* top to bottom */
flex-direction: column-reverse;
}
justify-content — Spacing Along the Main Axis
.container {
justify-content: flex-start; /* all items at start (default) */
justify-content: flex-end; /* all items at end */
justify-content: center; /* all items in centre */
justify-content: space-between; /* first and last at edges, equal gaps between */
justify-content: space-around; /* equal space around all items */
justify-content: space-evenly; /* equal space including edges */
}
align-items — Alignment on the Cross Axis
.container {
align-items: stretch; /* items fill the height (default) */
align-items: flex-start; /* items align to top */
align-items: flex-end; /* items align to bottom */
align-items: center; /* items align to vertical middle */
}
gap — Space Between Items
.card-grid {
display: flex;
gap: 24px; /* same gap in all directions */
gap: 16px 24px; /* row-gap | column-gap */
}
flex-wrap — Wrapping to New Lines
.card-grid {
display: flex;
flex-wrap: wrap; /* wrap to next line when no space */
gap: 20px;
}
.card {
flex: 1 1 300px; /* grow | shrink | minimum width */
}
Real-World Examples
Centered Hero Section
.hero {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 80vh;
text-align: center;
gap: 16px;
}
Card Grid
.cards {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.card {
flex: 1 1 280px; /* minimum 280px, grows to fill space */
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 24px;
}
Navbar
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 32px;
background: #1a1a2e;
}
.nav-links {
display: flex;
gap: 8px;
align-items: center;
}
Try It Yourself
- Use
display: flex; justify-content: center; align-items: center;to perfectly center a div - Build a navigation bar with logo on the left and links on the right using Flexbox
- Create a 3-card row that wraps to 1 column on small screens using
flex-wrap