By TailTemplate Team
In this tutorial, we will create a Tailwind CSS dropdown menu.
Firstly, let's style the drop menu using Tailwind CSS, in this step, we care nothing but the design of the menu.
Copy the following code:
<div class="flex-col flex items-start justify-start w-48">
<button class="px-4 py-2 bg-gray-50 rounded w-full">
Dropdown
</button>
<div class="flex flex-col items-center justify-center w-full">
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 1</a>
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 2</a>
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 3</a>
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 4</a>
</div>
</div>
It will create a static open state dropdown menu similar to this:
To modify the width of the dropdown menu, you can change the width of the outer container, it is currently set to w-48
.
We some Javascript to change the state(open/closed) dynamically. By default, it should be closed and when the user clicks the Dropdown
button, it will open. Close the menu again when leaving the menu.
AlpineJS is a nice and simple to use Javascript library for the dynamic UI component.
We are going to place some Alphinejs code to make our dropdown menu work.
In the header
section of the HTML, include the AlphineJS library:
<head>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
</head>
Add AlphineJS code snippet to our UI component:
<div class="flex-col flex items-start justify-start w-48" x-data="{ open: false }" @click.away="open = false">
<button class="px-4 py-2 bg-gray-50 rounded w-full" x-on:click="open=!open">
Dropdown
</button>
<div class="flex flex-col items-center justify-center w-full" x-bind:class="{'hidden':!open}">
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 1</a>
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 2</a>
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 3</a>
<a class="bg-gray-50 hover:bg-gray-200 w-full text-center py-2" href="#">Option 4</a>
</div>
</div>
x-data="{ open: false }" @click.away="open = false"
: create a local variable open
to represent the state, and set it to false by default. When a user clicks outside of the menu, we set it to false too: @click.away="open = false"
.x-on:click="open=!open"
: when user clicks the Dropdown
button, we toggle the state of open
variable.x-bind:class="{'hidden':!open}"
: we toggle a hidden
class in the selection element. This class is assigned/removed depending on the bool value of open
variable.With some simple Javascript's help, we have created a dynamic Tailwind CSS dropdown menu:
A project by StaticMaker.
This site is proudly powered by Tailwind CSS and Laravel Livewire