How to create a dropdown menu with AlpineJS + TailwindCSS

Step 1. Include all necessary assets on our page

<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

<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

<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>

Step 4. TailwindCSS

<!-- 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>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jian Jye

Jian Jye

47 Followers

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