CSS Navigation Bar
A horizontal navigation bar is one of the most common CSS layout exercises. Modern flexbox makes it almost trivial.
The HTML
HTML
<nav class="nav">
<a class="logo" href="/">iwantcoding.com</a>
<ul class="nav-links">
<li><a href="/html">HTML</a></li>
<li><a href="/css">CSS</a></li>
<li><a href="/js">JS</a></li>
</ul>
<a class="cta" href="/signup">Sign up</a>
</nav>
The CSS
CSS
.nav {
display: flex;
align-items: center;
gap: 24px;
padding: 12px 20px;
background: #282a35;
color: #fff;
}
.logo { font-weight: bold; color: #fff; text-decoration: none; }
.nav-links { list-style: none; display: flex; gap: 16px; margin: 0; padding: 0;
flex: 1; /* eat the spare room — pushes CTA to the right */ }
.nav-links a { color: #fff; text-decoration: none; padding: 8px 4px; }
.nav-links a:hover { border-bottom: 2px solid #04AA6D; }
.cta { background: #04AA6D; color: #fff; padding: 8px 14px; border-radius: 4px;
text-decoration: none; font-weight: bold; }
Common variations
| Variation | Add |
|---|---|
| Sticky to the top | .nav { position: sticky; top: 0; z-index: 10; } |
| Vertical sidebar | .nav { flex-direction: column; align-items: stretch; } |
| Collapse on mobile | A hamburger button + @media(max-width: 700px) hiding .nav-links by default. |
Tip:
flex: 1 on the link list is the easy way to push other items to the edges. No margin-left: auto gymnastics needed.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Navigation Bar</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Make the link list eat the spare room so the Sign-up button sits on the right.
.nav-links { display: flex; gap: 16px;
: 1; }
The shorthand that includes grow, shrink, and basis.
Discussion
Loading…