CSS Navigation Bar
CSS Navigation Bar: Responsive Flexbox Menus and Active States
A CSS navigation bar guides visitors across your website's main sections cleanly on both desktop monitors and narrow phone screens. Modern navbars combine semantic HTML (nav wrapping a ul list of links) with CSS Flexbox so branding, links, and call-to-action buttons align effortlessly.
Building a Clean Horizontal Navbar
First, strip list bullets and default padding from the ul (list-style: none; margin: 0; padding: 0;). Turn the header into a Flex container with justify-content: space-between; align-items: center;, and turn the link list into a flex row with gap: 8px; flex-wrap: wrap; so links never collide on narrower tablets.
.site-navbar {
position: sticky;
top: 0;
z-index: 40;
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 24px;
background-color: #0f172a;
color: #f8fafc;
}
.nav-links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.nav-links a {
display: block;
padding: 8px 14px;
color: #cbd5e1;
text-decoration: none;
border-radius: 6px;
}
.nav-links a:hover,
.nav-links a[aria-current="page"] {
background-color: #2563eb;
color: #ffffff;
}
Accessibility for Active Links
Instead of inventing only a .active class, add aria-current="page" on the active link in HTML and style a[aria-current="page"] in CSS. Screen readers announce the current page automatically while your CSS highlights it visually.
Common Mistakes to Avoid
- Floating navbar items with
float: left: Legacy float navbars require clearfixes and struggle with vertical centering; Flexbox handles vertical alignment in one line. - Setting fixed heights on single-line navbars without
flex-wrap: Long links wrap awkwardly outside fixed60pxbars on small screens; usemin-heightinstead. - Forgetting sufficient tap padding on mobile links: Give each link at least
8px 14pxpadding so touch targets are easy to tap.
Frequently Asked Questions
Should a navigation bar always wrap links inside a ul?
Wrapping links in a ul inside a labeled nav landmark is clean and widely used, though a flat list of a links directly inside nav is also valid HTML5.
How do I push a login button to the far right inside a Flexbox navbar?
Apply margin-left: auto; on the last li or button wrapper, or group left and right links in two containers with justify-content: space-between;.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.