0Pricing
Tailwind CSS Academy · Lesson

Collapsible Mobile Sidebar

Implement a slide-in drawer sidebar for mobile with a JavaScript toggle, overlay backdrop, and smooth translate transition.

What Is a Mobile Drawer Sidebar

A mobile drawer sidebar slides in from the left edge of the screen when a hamburger button is tapped, and slides out when dismissed. Unlike a desktop sidebar that is always visible, the mobile drawer is hidden off-screen by default using a CSS transform.

Three elements work together: the backdrop overlay that darkens the rest of the page, the sidebar panel that slides in, and the toggle button in the top bar that opens and closes the drawer.

<!-- Closed state: sidebar off-screen left -->
<aside id="drawer" class="fixed inset-y-0 left-0 w-72 bg-white z-50
                          -translate-x-full transition-transform duration-300">
  <!-- sidebar content -->
</aside>

<!-- Backdrop: hidden until drawer opens -->
<div id="backdrop" class="fixed inset-0 bg-black/50 z-40 hidden"></div>

The Open/Close JavaScript Toggle

The toggle works by removing the -translate-x-full class from the drawer and removing the hidden class from the backdrop. Closing reverses both operations.

A simple helper function openDrawer() and closeDrawer() keeps the logic clean. Add overflow-hidden to the body when the drawer is open to prevent scrolling the page content behind the overlay.

<script>
  const drawer = document.getElementById('drawer');
  const backdrop = document.getElementById('backdrop');

  function openDrawer() {
    drawer.classList.remove('-translate-x-full');
    backdrop.classList.remove('hidden');
    document.body.classList.add('overflow-hidden');
  }

  function closeDrawer() {
    drawer.classList.add('-translate-x-full');
    backdrop.classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
  }

  // Clicking backdrop closes the drawer
  backdrop.addEventListener('click', closeDrawer);
</script>

All lessons in this course

  1. Building a Responsive Navbar
  2. Sticky and Fixed Navigation
  3. Vertical Sidebar Layout
  4. Collapsible Mobile Sidebar
← Back to Tailwind CSS Academy