How to build a responsive navigation bar with Flexbox
· Category: HTML & CSS
Short answer
Use a <nav> container with display: flex, justify-content: space-between, and an unordered list. Add a media query to switch the layout to a vertical stack or toggle menu on small screens.
Steps
- Create a
<nav>with a logo and<ul>of links. - Apply
display: flexandalign-items: centerto the nav. - Use
gapormargin-left: autoto distribute items. - Add a hamburger button (hidden on desktop) and a media query to transform the layout.
Example
<nav class="navbar">
<a class="logo" href="/">Brand</a>
<ul class="nav-links">
<li><a href="/about">About</a></li>
<li><a href="/services">Services</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
<button class="toggle" aria-label="open menu">☰</button>
</nav>
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 2rem;
}
.nav-links {
display: flex;
gap: 1.5rem;
list-style: none;
}
@media (max-width: 600px) {
.nav-links {
display: none;
flex-direction: column;
}
.nav-links.open {
display: flex;
}
}
Tips
- Use
aria-expandedon the toggle button to indicate menu state. - Consider
position: stickyto keep the navbar visible while scrolling. - Test keyboard navigation to ensure the menu is fully accessible.