Very Simple Mobile Menu with TailwindCSS & AlpineJS

Posted 26th Mar 2020

Almost every new website I build requires some kind of menu that then needs to be hidden away into a panel or slide out version for use on mobile & tablet devices.

This is a small snippet of code that will give you a starting point for your header (complete with logo) that reduces down into a popout mobile menu.

I wanted to create this as there are a lot of examples of this out there, but many of them require the use of 2 sets of html markup for both the main menu and then the mobile menu. My version only uses one set of markup and a whole lot of tailwind classes to convert that same markup into a mobile menu.

Have a look at the code below. You can even just copy the div inside the <header> tags if you only need the menu markup and not the full header.

See the code snippet below or view the demo here.

<header class="bg-white border-b px-6 py-4 flex justify-between items-center">
  <a href="#" class="block">
    <img src="" class="h-12 w-auto" />

  <div x-data="{ open: false }">

    <div :class="{ 'block' : open, 'hidden' : open === false }" class="fixed md:relative top-0 left-0 w-full md:w-auto h-screen md:h-auto flex md:block flex-col items-center justify-center z-40 bg-white leading-loose font-sans uppercase text-gray-800 text-sm tracking-wide">
      <a href="#">Home</a>
      <a href="#" class="md:ml-4">About Us</a>
      <a href="#" class="md:ml-4">Contact Us</a>

    <button @click="open = true" type="button" :class="{ 'hidden' : open, 'block' : !open }" class="block md:hidden text-4xl font-thin">=</button>

    <button @click="open = false" type="button" :class="{ 'block' : open, 'hidden' : !open }" class="md:hidden absolute top-0 right-0 leading-none p-8 text-xl z-50">╳</button>