How to create a dropdown menu with AlpineJS + TailwindCSS

Jian Jye
2 min readApr 24, 2021

AlpineJS is great as a jQuery replacement when you need to perform some simple Javascript operation like opening and closing a dropdown menu. Dropdown menu is now increasingly popular as a UI choice and here we’ll learn how to create the menu easily with AlpineJS and TailwindCSS.

Step 1. Include all necessary assets on our page

We’ll need both AlpineJS and TailwindCSS. For simplicity, we can pull them from the cloud directly:

<head>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<style>
[x-cloak] {
display: none !important;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.8.2/dist/alpine.min.js" defer></script>
</head>

Step 2. Let’s build the basic HTML structure

Without all the stylings, our raw HTML structure with only the essential positional CSS would look like this:

<div>
<div>
<div class="relative">
<div>Logan Nathan</div>
<div class="absolute origin-top-right top-6 right-0">
<div>
<a href="/logout">Sign Out</a>
</div>
</div>
</div>
</div>
</div>

Step 3. Let’s add the AlpineJS magic

Now, with just some extra AlpineJS codes, we can already make it functional:

<div>
<div x-data="{open: false}" @mouseover="open = true" @mouseleave="open = false">
<div class="relative">
<div>Logan Nathan</div>
<div class="absolute origin-top-right top-6 right-0" x-show="open" x-cloak>
<div>
<a href="/logout">Sign Out</a>
</div>
</div>
</div>
</div>
</div>

But the position of it might be off ya. So let’s add some Tailwind styling to the codes.

Step 4. TailwindCSS

Finally, to make it look / work better, here are the TailwindCSS codes added:

<!-- You could replace the parent container with your own container -->
<div class="flex">
<div class="py-2" x-data="{open: false}" @mouseover="open = true" @mouseleave="open = false">
<div class="relative flex items-center space-x-1 cursor-pointer text-sm font-medium">
<div>Logan Nathan</div>
<div class="origin-top-right absolute top-6 right-0 w-24 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none" x-show="open" x-cloak>
<div class="py-1">
<a href="/logout" class="text-gray-700 block px-4 py-2 text-sm">Sign Out</a>
</div>
</div>
</div>
</div>
</div>

Voila! You now have a working dropdown menu!

I have also created a CodePen here. If you could not get it to work you can refer to the demo there. Thanks!

--

--

Jian Jye

I write about Laravel, PHP, and web development related articles.