onClick
Published on

Multi-level Dropdown with Tailwind CSS / Alpine.js

Authors

Multi-level Dropdown

Before we start, you should have a basic understanding of HTML, CSS, and JavaScript. You should also have Tailwind CSS and Alpine.js installed in your project.

form

Getting Started

Install Tailwind CSS

Install Alpine.js

Code

To create our multi-level dropdown menu, we will start by setting up the HTML structure. We will use the x-data directive to create a reactive data object that we will use to control the visibility of our dropdown menu.

<div x-data="{ show: false, menu: false }">
    <button class="text-sm text-white bg-blue-800 px-4 py-2 border-0 rounded-md outline-none hover:bg-blue-900"
        x-on:click="show = ! show">Open Dropdown</button>
    <div class="relative">
        <div class="bg-gray-800 rounded-md p-3 min-w-[220px] top-1 w-full absolute z-10" x-show="show"
            x-cloak
            @click.away="show = false" x-transition:enter="transition ease-out duration-100"
            x-transition:enter-start="transform opacity-0 scale-95">
            <ul
                class="[&>li]:text-white [&>li]:text-sm [&>li]:cursor-pointer [&>li]:px-2 [&>li]:py-1 [&>li]:rounded-md [&>li]:transition-all hover:[&>li]:bg-gray-600 active:[&>li]:bg-gray-700 active:[&>li]:scale-[0.99]">
                <li>Profile</li>
                <li>Dashboard</li>
                <li>Settings</li>
                <li class="flex items-center justify-between" 
                    x-on:click="menu = ! menu" 
                    @click.away="menu = false"
                    >
                    Services
                    <i class="arrow"></i>
                </li>
                <div class="bg-gray-800 rounded-md max-w-[180px] w-full p-3 absolute -right-[185px] -bottom-4 [&>li]:text-white [&>li]:text-sm [&>li]:cursor-pointer [&>li]:px-2 [&>li]:py-1 [&>li]:rounded-md [&>li]:transition-all hover:[&>li]:bg-gray-600 active:[&>li]:bg-gray-700 active:[&>li]:scale-[0.99]"
                    x-show="menu" x-transition:enter="transition ease-out duration-100"
                    x-transition:enter-start="transform opacity-0 scale-95">
                    <li>List Item #1</li>
                    <li>List Item #2</li>
                    <li>List Item #3</li>
                </div>
                <div class="w-full border border-gray-700 my-1"></div>
                <li>Logout</li>
            </ul>
        </div>
    </div>
</div>

I created arrow with CSS

.arrow {
    border: solid white;
    border-width: 0 2px 2px 0;
    display: inline-block;
    padding: 3px;
    transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
}

You can access the full code: Multi-level Dropdown

  • avatar
    Name
    Umur Köse
    Twitter
    Twitter