Master creating a responsive navbar from scratch with HTML and CSS. Enhance your site’s navigation for all devices, step-by-step!
Table of content
Navigation bars (navbars) play a critical role in website usability. A responsive navbar ensures your menu adapts gracefully for desktops, tablets, and mobile devices, maximizing accessibility and user experience. In this guide, you’ll learn how to build a modern responsive navbar from scratch using only HTML and CSS.
<nav class="navbar">
<div class="brand">fulldev.pl</div>
<button class="toggle" aria-label="Toggle menu">☰</button>
<ul class="nav-links">
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
Start by creating the desktop layout. We’ll hide the toggle button by default and arrange items horizontally.
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
background: #24292f;
color: #fff;
padding: 0.8rem 1.5rem;
}
.brand {
font-weight: bold;
font-size: 1.2rem;
}
.nav-links {
display: flex;
list-style: none;
gap: 1.2rem;
margin: 0;
padding: 0;
}
.nav-links a {
color: #fff;
text-decoration: none;
transition: color 0.2s;
}
.nav-links a:hover {
color: #ffa000;
}
.toggle {
display: none;
background: none;
border: none;
color: #fff;
font-size: 2rem;
cursor: pointer;
}
On small screens, we’ll stack links vertically and show the menu toggle button.
@media (max-width: 800px) {
.nav-links {
display: none;
position: absolute;
top: 60px;
right: 0;
left: 0;
background: #24292f;
flex-direction: column;
text-align: center;
gap: 0;
}
.nav-links.open {
display: flex;
}
.toggle {
display: block;
}
.navbar {
position: relative;
}
}
If you want to create a toggle with pure CSS, you need a checkbox hack. For production use, you may prefer JavaScript for accessibility, but here’s a common CSS approach:
<input type="checkbox" id="menu-toggle" style="display:none;" />
<label for="menu-toggle" class="toggle" aria-label="Toggle menu">☰</label>
<ul class="nav-links"> ... </ul>
#menu-toggle:checked ~ .nav-links {
display: flex;
}
Here’s a simple script to toggle the menu. This ensures keyboard and accessibility support:
const toggleBtn = document.querySelector('.toggle');
const navLinks = document.querySelector('.nav-links');
toggleBtn.addEventListener('click', () => {
navLinks.classList.toggle('open');
});
With this approach, you can customize and expand your navbar to fit any project on fulldev.pl!