Tutorials CSS Project: Responsive Navbar
Ch 57 / 60
Chapter 57 Project 14 min build CSS

Project: Responsive Navbar

Every real website needs a navbar that works everywhere — full links on desktop, a clean hamburger toggle on mobile. This project combines flexbox layout, a CSS-only hamburger-to-X animation, a hover dropdown submenu, and a slide-in mobile panel — using just a few lines of JavaScript to toggle one class, with CSS handling 100% of the actual animation and layout logic.

↑ This is the actual finished desktop navbar. Hover "Courses" to see the dropdown.

What you'll build
Flexbox navbar: logo, links, CTA button
Hover dropdown submenu
CSS-only hamburger-to-X animation
Slide-in mobile menu panel
Media query breakpoint switch
Keyboard-accessible focus states

Step 1 — HTML Structure

The structure needs to support BOTH desktop and mobile states without duplicating markup — the same <ul> of links is reused, just shown differently via CSS depending on screen size:

HTML — navbar markup
<nav class="navbar">
  <div class="nav-logo">K2<span>infocom</span></div>

  <ul class="nav-links" id="navLinks">
    <li><a href="#">Home</a></li>

    <!-- dropdown item -->
    <li class="has-dropdown">
      <a href="#">Courses</a>
      <div class="dropdown-menu">
        <a href="#">Web Development</a>
        <a href="#">Python Masterclass</a>
      </div>
    </li>

    <li><a href="#">Blog</a></li>
  </ul>

  <a href="#" class="nav-cta">Get Started</a>

  <!-- hamburger — only visible below the breakpoint -->
  <button class="hamburger" id="hamburgerBtn" aria-label="Menu">
    <span></span><span></span><span></span>
  </button>
</nav>

Step 2 — Desktop Flexbox Layout

One flexbox row with justify-content: space-between spaces the logo, links, and CTA apart automatically — no manual margins needed:

CSS — base navbar layout
.navbar {
  display:        flex;
  align-items:    center;
  justify-content:space-between;   /* logo ←→ links ←→ CTA */
  padding:        14px 22px;
  background:     #0f172a;
}

.nav-logo {
  color:        #fff;
  font-weight:  800;
  font-size:    16px;
}
.nav-logo span { color: #4a8af4; }   /* accent on the second word */

.nav-links {
  display:     flex;
  gap:         26px;
  list-style:  none;
}
.nav-links a {
  color:           #cbd5e1;
  font-size:       13px;
  font-weight:     600;
  text-decoration:none;
  transition:      color .2s;
}
.nav-links a:hover { color: #fff; }

.nav-cta {
  background:     #264de4;
  color:          #fff;
  padding:        8px 18px;
  border-radius:  7px;
  font-weight:    700;
  text-decoration:none;
  transition:     background .2s;
}
.nav-cta:hover { background: #1d3eb8; }

Step 3 — Hover Dropdown Submenu

The dropdown is absolutely positioned relative to its parent <li>, hidden by default with opacity and visibility (not display: none, which can't be transitioned), and revealed using :hover — paired with :focus-within so keyboard users tabbing through links can open it too:

CSS — dropdown submenu
.has-dropdown { position: relative; }   /* anchor for the absolute dropdown */

.dropdown-menu {
  position:    absolute;
  top:         130%; left: 0;
  background:  #1e293b;
  border-radius:8px;
  min-width:   160px;
  padding:     6px;
  box-shadow:  0 12px 24px rgba(0,0,0,.3);

  /* hidden state — opacity/visibility, NOT display:none, so it can transition */
  opacity:     0;
  visibility:  hidden;
  transform:   translateY(-6px);
  transition:  opacity .2s, transform .2s, visibility .2s;
}

/* ── Reveal on hover AND keyboard focus ── */
.has-dropdown:hover .dropdown-menu,
.has-dropdown:focus-within .dropdown-menu {
  opacity:    1;
  visibility: visible;
  transform:  translateY(0);
}

.dropdown-menu a {
  display:        block;
  padding:        8px 10px;
  border-radius:  6px;
  font-size:      12px;
}
.dropdown-menu a:hover { background: rgba(255,255,255,.06); }

/* Why opacity/visibility instead of display:none?
   display has no intermediate state to animate — it's either
   "there" or "not there" with no transition possible.
   opacity + visibility can both transition smoothly, AND
   visibility:hidden (unlike opacity:0 alone) also removes
   the dropdown from tab order / click-through when hidden. */

Step 4 — Hamburger-to-X Animation

Three stacked <span> bars form the hamburger icon. Toggling one class on the button rotates the top and bottom bars into an X and hides the middle bar — pure CSS transforms and transitions, no animation library:

Live demo — click to toggle

Click the icon — top/bottom bars rotate 45°, middle bar fades out

CSS — hamburger to X transform
.hamburger {
  width:          40px; height: 40px;
  display:        none;        /* hidden on desktop, shown below breakpoint */
  flex-direction: column;
  align-items:    center;
  justify-content:center;
  gap:            5px;
  background:     #0f172a;
  border:         none;
  border-radius:  8px;
  cursor:         pointer;
}

.hamburger span {
  width:         20px; height: 2px;
  background:    #fff;
  border-radius: 1px;
  transition:    transform .25s, opacity .25s;  /* on resting state */
}

/* ── When .is-open class is toggled (via small JS click handler) ── */
.hamburger.is-open span:nth-child(1) {
  transform: translateY(7px) rotate(45deg);   /* move down, rotate to form top-left of X */
}
.hamburger.is-open span:nth-child(2) {
  opacity: 0;                              /* middle bar vanishes */
}
.hamburger.is-open span:nth-child(3) {
  transform: translateY(-7px) rotate(-45deg);  /* move up, rotate opposite direction */
}

/* Minimal JS needed — CSS does the animation, JS only toggles the class */
/* hamburgerBtn.addEventListener('click', () => {
     hamburgerBtn.classList.toggle('is-open');
     mobileMenu.classList.toggle('is-open');
   }); */

Step 5 — Mobile Slide-in Menu & Breakpoint

Below the breakpoint, the desktop link list hides, the hamburger appears, and a full-height panel slides in from the right using transform: translateX() — never animating left or width, which would force layout recalculation on every frame:

Closed
Open — translateX(0)
CSS — mobile breakpoint and slide-in panel
/* ── Mobile menu panel — slides in from the right ── */
.mobile-menu {
  position:   fixed;
  top: 0; right: 0; bottom: 0;
  width:      75%; max-width: 320px;
  background: #264de4;
  padding:    70px 24px;
  display:    flex; flex-direction: column; gap: 14px;

  /* hidden state — pushed fully off-screen to the right */
  transform:  translateX(100%);
  transition: transform .3s ease;
}
.mobile-menu.is-open { transform: translateX(0); }   /* slides into view */

.mobile-menu a {
  color:        #fff;
  font-weight: 600;
  padding-bottom: 14px;
  border-bottom: 1px solid rgba(255,255,255,.15);
}

/* ── Breakpoint switch — show/hide desktop vs mobile elements ── */
@media (max-width: 768px) {
  .nav-links  { display: none; }   /* hide desktop link row */
  .nav-cta    { display: none; }   /* hide desktop CTA, move into mobile menu instead */
  .hamburger { display: flex; }   /* show the hamburger */
}

/* Why transform: translateX() instead of animating "right" or "left"?
   transform is handled by the GPU and doesn't trigger layout
   recalculation — animating left/right/width forces the browser
   to recompute the layout of surrounding elements on every frame,
   causing visible jank, especially on lower-powered devices. */

Component Anatomy Reference

Element Key CSS Why
.navbar display:flex, justify-content:space-between Spaces logo/links/CTA without manual margins
.has-dropdown position:relative Positioning context for the absolute dropdown
.dropdown-menu opacity/visibility (not display), :hover + :focus-within Animatable, keyboard-accessible reveal
.hamburger span transform:rotate(), opacity, transition Pure-CSS X animation, no JS animation needed
.mobile-menu position:fixed, transform:translateX() GPU-accelerated slide, avoids layout thrash
@media (max-width:768px) display:none / display:flex toggles Switches between desktop and mobile UI at the breakpoint
Free Resource
CSS3 Cheat Sheet — Navigation & Component Patterns
Complete reference covering responsive navbars, dropdowns, and mobile menu patterns.
Download PDF

Try It Yourself

The complete navbar — resize the preview pane below 768px wide to see it switch from the desktop layout to the hamburger + slide-in mobile menu:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 57

Questions & Answers
display: none removes an element from the rendering process entirely — it has no intermediate state, so the browser can't animate between "displayed" and "not displayed." A transition declared on the display property does nothing visually; the element simply pops in or out instantly.

opacity and visibility, on the other hand, are both fully animatable. opacity: 0 → 1 fades the dropdown in smoothly. But opacity alone has a problem: even at opacity: 0, the element is still technically "there" — it remains clickable and tabbable, just invisible, which can trap keyboard focus or let a user accidentally click a hidden link.

Adding visibility: hidden alongside opacity solves this: when hidden, the element becomes truly non-interactive (un-clickable, removed from tab order), but unlike display: none, visibility can still participate in a CSS transition, so the combination gives you both a smooth fade AND proper non-interactivity while hidden.
:hover only triggers from mouse movement — a keyboard-only user tabbing through the navbar with the Tab key never "hovers" anything, so a dropdown that only responds to :hover would be completely inaccessible to them; they'd tab past the "Courses" link with no way to reveal or interact with the submenu items at all.

:focus-within matches an element if it OR any of its descendants currently has keyboard focus. By writing .has-dropdown:focus-within .dropdown-menu { opacity: 1; ... }, the moment a keyboard user tabs onto the "Courses" link (which is inside .has-dropdown), the dropdown reveals itself exactly as it would on hover — and stays open as they continue tabbing into the dropdown's own links.

Combining both pseudo-classes with a comma (:hover, :focus-within) means the same dropdown works correctly for both mouse and keyboard users, which is a core accessibility requirement for any interactive navigation pattern.
Animating positional properties like left, right, or width forces the browser to recompute layout (a "reflow") on every single frame of the animation — the browser has to figure out how this changing box affects the position of every other element around it, which is computationally expensive and can cause visible stuttering, especially on lower-powered mobile devices (ironically, exactly where this menu pattern is used most).

transform properties (including translateX) are handled differently by the browser's rendering engine — they're composited on the GPU and don't trigger a layout recalculation at all. The element visually moves, but the browser doesn't need to ask "how does this affect everything else on the page" because transform doesn't change the element's actual position in the layout flow, just how it's painted on screen.

This is why transform: translateX(100%) (hidden, pushed fully off-screen) to translateX(0) (visible) is the standard, performant way to build slide-in panels, rather than animating right: -300px to right: 0.
JavaScript's only job in this pattern is toggling one CSS class (.is-open) on the hamburger button when clicked — a single line, btn.classList.toggle('is-open'). Every visual change from that point forward is handled entirely by CSS.

The three <span> bars each have a transition declared on their resting state for transform and opacity. When .is-open is added to the parent, three new CSS rules immediately apply: the first bar gets transform: translateY(7px) rotate(45deg) (moves down and rotates to form the upper-left stroke of an X), the second bar gets opacity: 0 (disappears, since an X only needs two strokes), and the third bar gets transform: translateY(-7px) rotate(-45deg) (moves up and rotates the opposite direction to form the lower-right stroke).

Because the transition was already declared on the resting state, the browser automatically animates between the old and new transform/opacity values smoothly — no keyframes, no animation library, and removing the class reverses the entire animation automatically back to the hamburger shape.
On desktop, the navbar has three distinct flex items spread across the row: the logo, the link list, and the CTA button — all visible simultaneously since there's enough horizontal space. On a narrow mobile viewport, there usually isn't room for all three plus a hamburger icon without overcrowding the bar.

The standard mobile navbar pattern condenses everything into just two visible elements at the top: the logo and the hamburger toggle. Both the link list AND the CTA button move into the slide-in mobile menu panel instead, where they're listed vertically with plenty of room — the mobile menu's HTML in this project repeats the same links plus a final "Get Started" link, recreating the CTA inside the panel rather than leaving it cramped in the top bar.

This is why the media query hides both .nav-links and .nav-cta together — they're both desktop-only elements that get replaced by the unified mobile menu panel, not partially kept and partially hidden.
Multiple Choice Questions
Question 1 of 5
What CSS property combination makes the dropdown menu animatable while still being non-interactive when hidden?
Question 2 of 5
What does adding :focus-within to the dropdown selector achieve?
Question 3 of 5
Why is transform: translateX() preferred over animating the right property for the slide-in mobile menu?
Question 4 of 5
How much JavaScript is needed for the hamburger-to-X animation itself?
Question 5 of 5
What does the media query at the mobile breakpoint do to .nav-links and .nav-cta?
Chapter Summary
  • Desktop layout: single flexbox row with justify-content: space-between spaces logo, links, and CTA automatically.
  • Dropdown submenu: position: relative on the parent li, position: absolute on the dropdown. Hidden via opacity: 0; visibility: hidden (not display: none) so it remains animatable.
  • Accessibility: reveal the dropdown on both :hover AND :focus-within so keyboard-only users can access it too.
  • Hamburger-to-X: three spans, each with its own transform + opacity transition declared at rest. Toggling one parent class (.is-open) changes all three simultaneously — zero JS animation code.
  • Mobile slide-in panel: position: fixed + transform: translateX(100%→0), never animating left/right/width directly — transform is GPU-composited and avoids layout thrash.
  • Breakpoint switch: a single media query toggles display: none ↔ flex on the desktop link row, CTA, and hamburger — both desktop elements move into the unified mobile panel below the breakpoint.
  • JavaScript's only role: toggling one class on click (classList.toggle('is-open')) — every visual transition is handled by CSS.
~14 min build
Project chapter
Chapter 57 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel