Building a Mobile-Responsive Navigation Menu With Tailwind CSS
Responsive navigation is essential for creating user-friendly websites that work well across devices. In this tutorial, we'll build a sleek, mobile-responsive navigation bar using Tailwind CSS, complete with a hamburger menu for small screens.
Step 1: Basic HTML Structure
We’ll start with a basic navigation bar layout.
<nav class="bg-white shadow-md p-4"> <div class="container mx-auto flex items-center justify-between"> <div class="text-xl font-bold">MySite</div> <div class="md:hidden"> <button id="menu-btn" class="focus:outline-none"> ☰ </button> </div> <ul id="menu" class="hidden md:flex space-x-6"> <li><a href="#" class="hover:text-blue-500">Home</a></li> <li><a href="#" class="hover:text-blue-500">About</a></li> <li><a href="#" class="hover:text-blue-500">Services</a></li> <li><a href="#" class="hover:text-blue-500">Contact</a></li> </ul> </div> </nav>
Step 2: Add Tailwind Classes for Responsive Behavior
We’ve already used md:hidden
and md:flex
to control when elements appear. Now let's add a little JavaScript to toggle the menu on mobile.
Step 3: Toggle Menu With JavaScript
<script> const menuBtn = document.getElementById('menu-btn'); const menu = document.getElementById('menu'); menuBtn.addEventListener('click', () => { menu.classList.toggle('hidden'); }); </script>
Step 4: Optional Enhancements
- Add transitions or animations for smoother effects.
- Replace the ☰ icon with an SVG hamburger icon for better styling.
- Highlight the active link with
font-bold
or a border.
Conclusion
Tailwind CSS makes it easy to build responsive navigation without writing custom media queries. With a simple toggle and a few utility classes, your site is now mobile-ready!
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)