Navigation Bar with Flexbox
Build a responsive navigation bar using CSS Flexbox. Logo on the left, nav links in the center or right, and action buttons aligned to the end.
Detailed Explanation
Flexbox Navigation Bar
A navigation bar is one of the most common use cases for Flexbox. It typically has a logo on the left, navigation links distributed in the middle or right, and action buttons at the far right.
CSS Code
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 24px;
height: 64px;
}
.logo {
flex: 0 0 auto;
}
.nav-links {
display: flex;
gap: 24px;
flex: 1;
justify-content: center;
}
.actions {
flex: 0 0 auto;
display: flex;
gap: 8px;
}
How It Works
The navbar uses nested flex containers:
- Outer container:
justify-content: space-betweenpushes logo and actions to opposite ends. - Nav links: A nested flex container with
flex: 1takes all remaining space andjustify-content: centercenters the links within that space. - Logo and Actions:
flex: 0 0 automeans they stay at their natural widths.
Spacing Strategies
| Pattern | CSS | Result |
|---|---|---|
| Centered links | flex: 1; justify-content: center |
Links centered between logo and actions |
| Right-aligned links | margin-left: auto on nav-links |
Links pushed to the right |
| Evenly spaced | justify-content: space-evenly on parent |
All sections evenly distributed |
Mobile Hamburger Menu
On small screens, hide the nav links and show a hamburger button:
@media (max-width: 768px) {
.nav-links {
display: none;
}
.hamburger {
display: flex;
}
}
The Flexbox layout of the navbar itself does not change — only the visibility of its children toggles.
Sticky Navbar
Add position: sticky; top: 0; z-index: 50; to keep the navbar visible while scrolling.
Use Case
Use this pattern for website headers, application top bars, dashboard navigation, or any horizontal menu component. The Flexbox approach ensures proper alignment across different screen sizes with minimal CSS.