A CSS navigation bar turns HTML unordered lists (<ul>) into horizontal or vertical site navigation menus using Flexbox, hover states, and active link indicators.
Navigation menus are built by styling list containers and anchor tags:
/* Horizontal Navigation Bar with Flexbox */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #1e293b;
padding: 1rem 2rem;
}
.nav-links {
list-style: none;
display: flex;
gap: 1.5rem;
margin: 0;
padding: 0;
}
.nav-links a {
color: #f8fafc;
text-decoration: none;
transition: color 0.2s ease;
}
.nav-links a:hover {
color: #38bdf8;
}
Menu construction steps:
list-style: none; margin: 0; padding: 0; on the <ul> list.display: flex; gap: 1.5rem; on the list wrapper.<a> tags.flowchart LR
A["Navbar (display: flex)"] --> B["Brand Logo"]
A --> C["Nav Links List (display: flex; gap: 1.5rem)"]
C --> C1["Link 1"]
C --> C2["Link 2"]
C --> C3["Link 3"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Navigation Bar Example</title>
<style>
.nav-header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #1e293b;
padding: 1rem 2rem;
border-radius: 8px;
}
.brand-title {
color: #38bdf8;
font-weight: bold;
font-size: 1.25rem;
}
.nav-list {
list-style: none;
display: flex;
gap: 1rem;
margin: 0;
padding: 0;
}
.nav-item a {
color: #94a3b8;
text-decoration: none;
padding: 8px 12px;
border-radius: 4px;
transition: all 0.2s ease;
}
.nav-item a:hover, .nav-item a.active {
color: #ffffff;
background-color: #334155;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<header class="nav-header">
<div class="brand-title">KoderSolution</div>
<ul class="nav-list">
<li class="nav-item"><a href="#" class="active">Home</a></li>
<li class="nav-item"><a href="#">Docs</a></li>
<li class="nav-item"><a href="#">Blog</a></li>
</ul>
</header>
</body>
</html>
<header> and <nav> semantic layout containers: Wrap navigation menus in <nav> for screen reader accessibility.gap for link spacing: Use gap: 1rem; on flex wrappers instead of applying margin-right to list items..active class: Highlight the current page link visually.Create a CSS rule for .nav-list setting display: flex; list-style: none; gap: 1.5rem;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.