DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Responsive Navbar with Pure CSS

Every website needs a navbar, and the responsive version — links on desktop, hamburger menu on mobile — is a perfect beginner project. It teaches flexbox, media queries, and the checkbox hack that gives you a working mobile menu with zero JavaScript.

The HTML is a header with a logo, a hidden checkbox, a label that becomes the hamburger, and the nav links:

<header class="navbar">
  <a href="#" class="logo">MySite</a>
  <input type="checkbox" id="menu-toggle">
  <label for="menu-toggle" class="hamburger">☰</label>
  <nav class="links">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Blog</a>
    <a href="#">Contact</a>
  </nav>
</header>
Enter fullscreen mode Exit fullscreen mode

On desktop, flexbox spreads the logo left and the links right:

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #111;
}

.links {
  display: flex;
  gap: 24px;
}

.links a {
  color: #fff;
  text-decoration: none;
}

#menu-toggle,
.hamburger {
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

The checkbox hack is the trick: the checkbox is hidden, the label toggles it, and CSS reacts to :checked. On mobile the links become a dropdown that appears only when the checkbox is checked:

@media (max-width: 640px) {
  .hamburger {
    display: block;
    color: #fff;
    font-size: 24px;
    cursor: pointer;
  }

  .links {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    flex-direction: column;
    background: #111;
    padding: 16px;
  }

  #menu-toggle:checked ~ .links {
    display: flex;
  }
}
Enter fullscreen mode Exit fullscreen mode

The ~ sibling selector is what makes it work: when the checkbox is checked, the following .links element shows. No JavaScript, no framework, and it works even with scripting disabled.

Two details make it feel finished. First, make the header sticky so the navbar stays visible while scrolling — position: sticky; top: 0 on the header. Second, add an active state to the current page link so users always know where they are.

Ways to extend it: add a dropdown submenu with pure CSS :hover and :focus-within, animate the mobile menu sliding down with a max-height transition, or replace the checkbox hack with a few lines of JavaScript once you are comfortable — the CSS version teaches you the selectors, the JS version teaches you state.

Top comments (0)