This snippet demonstrates how to create a responsive navigation bar that adapts seamlessly to different screen sizes.
Using HTML for structure, CSS for styling and layout, and JavaScript for interactivity, the navbar includes features like a menu links and collapsible menu toggle for mobile devices.
<header>
<nav class="navbar">
<div class="logo">
<a href="#">Brand</a>
</div>
<ul class="nav-links" id="nav-links">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
<div class="hamburger" id="hamburger">
☰
</div>
</nav>
</header>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
}
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background-color: #333;
color: white;
}
.navbar .logo a {
font-size: 1.8rem;
color: white;
text-decoration: none;
}
.nav-links {
list-style-type: none;
display: flex;
}
.nav-links li {
margin-left: 20px;
}
.nav-links a {
color: white;
text-decoration: none;
padding: 10px;
display: block;
}
.hamburger {
display: none;
font-size: 2rem;
cursor: pointer;
}
@media (max-width: 768px) {
.nav-links {
display: none;
position: absolute;
top: 60px;
right: 0;
background-color: #333;
width: 100%;
text-align: center;
padding: 1rem 0;
}
.nav-links li {
margin: 0;
padding: 10px 0;
}
.nav-links.active {
display: block;
}
.hamburger {
display: block;
}
}
const hamburger = document.getElementById('hamburger');
const navLinks = document.getElementById('nav-links');
if (hamburger && navLinks) {
hamburger.addEventListener('click', function () {
navLinks.classList.toggle('active');
});
}