CSS Navigation Bars
On this page
CSS Navigation Bars
A navigation bar (navbar) is a set of links that helps users move around a website. Navbars can be built with lists and styled using CSS to create vertical or horizontal menus.
A common pattern is to use an unordered list (ul) and remove default list styling.
Navbar Intro
This is a simple HTML structure for a navbar:
<ul class="nav"> <li><a href="#">Home</a></li> <li><a href="#">Tutorials</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul>
We start by resetting the list and styling the links:
.nav {
list-style: none;
padding: 0;
margin: 0;
}
.nav a {
display: block;
padding: 10px 14px;
text-decoration: none;
color: #222;
border-radius: 10px;
}
.nav a:hover {
background: #eef3ff;
color: #1f4bd8;
}
Vertical Navbar
A vertical navbar is the default layout for list items. Each link takes a full row.
.nav-vertical {
list-style: none;
padding: 0;
margin: 0;
max-width: 260px;
}
.nav-vertical li {
margin-bottom: 8px;
}
.nav-vertical a {
display: block;
padding: 10px 14px;
border: 1px solid #eee;
border-radius: 10px;
text-decoration: none;
color: #222;
}
.nav-vertical a:hover {
background: #eef3ff;
border-color: #d6e4ff;
color: #1f4bd8;
}
Horizontal Navbar
To create a horizontal navbar, you can use Flexbox on the list and place items side by side.
.nav-horizontal {
list-style: none;
padding: 10px;
margin: 0;
display: flex;
gap: 10px;
border: 1px solid #eee;
border-radius: 12px;
}
.nav-horizontal a {
display: block;
padding: 10px 14px;
border-radius: 10px;
text-decoration: none;
color: #222;
}
.nav-horizontal a:hover {
background: #eef3ff;
color: #1f4bd8;
}
You can also create an “active” link style to show the current page:
.nav-horizontal a.active {
background: #1f4bd8;
color: #fff;
}
Code Challenge
Goal: Build a horizontal navbar with hover and active states.
HTML:
<ul class="nav-horizontal"> <li><a class="active" href="#">Home</a></li> <li><a href="#">Docs</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact</a></li> </ul>
Task:
- Remove list styling and align items horizontally
- Add spacing between items
- Add hover background
- Add an active style for the current page
Try a Solution:
.nav-horizontal {
list-style: none;
margin: 0;
padding: 10px;
display: flex;
gap: 10px;
border: 1px solid #eee;
border-radius: 12px;
}
.nav-horizontal a {
display: block;
padding: 10px 14px;
border-radius: 10px;
text-decoration: none;
color: #222;
}
.nav-horizontal a:hover {
background: #eef3ff;
color: #1f4bd8;
}
.nav-horizontal a.active {
background: #1f4bd8;
color: #fff;
}
What’s Next?
Next, you will learn how to create dropdown menus using CSS.