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.

Common Components

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:

  1. Outer container: justify-content: space-between pushes logo and actions to opposite ends.
  2. Nav links: A nested flex container with flex: 1 takes all remaining space and justify-content: center centers the links within that space.
  3. Logo and Actions: flex: 0 0 auto means 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.

Try It — Flexbox Playground

Open full tool