Tailwind CSS: How to Create a Hoverable Dropdown Menu

Updated: June 9, 2022 By: Pennywise 3 comments

This concise article shows you how to create a hover dropdown menu with Tailwind CSS. No Javascript code is required.

A dropdown menu is a toggleable menu that allows the user to select an option or go to a link from a list of items. A hover dropdown menu will be opened when the user’s mouse hovers over a certain area (e.g., a button). It will help your website save space and only show the menu as needed.

Example

Preview:

The code:

<body class="p-20 flex flex-col space-y-10 bg-yellow-100">
    <h2 class="text-2xl italic">Hoverable Dropdown Menu by KindaCode.com</h2>

    <div>
        <button class="peer px-5 py-2 bg-green-600 hover:bg-green-700 text-white">Dropdown</button>
        
        <!-- the menu here -->
        <div class="hidden peer-hover:flex hover:flex
         w-[200px]
         flex-col bg-white drop-shadow-lg">
            <a class="px-5 py-3 hover:bg-gray-200" href="#">About Us</a>
            <a class="px-5 py-3 hover:bg-gray-200" href="#">Contact Us</a>
            <a class="px-5 py-3 hover:bg-gray-200" href="#">Privacy Policy</a>
        </div>
    </div>
</body>

Code explained:

  • We add the peer class to the button so that we can style the menu based on the button’s state (with the peer-hover modifier). In the beginning, the menu is hidden (with the hidden utility). When the mouse cursor hovers over the button, the menu will show up (with peer-hover:flex).
  • The menu still needs to be displayed when the mouse pointer moves over its items. That’s why we use hover:flex.
  • In addition to the above important points, we also give the menu a drop shadow and style its items to make it more elegent.

Further reading:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
3 Comments
Inline Feedbacks
View all comments
Mehmed Bin Murad
Mehmed Bin Murad
8 months ago

Its okay but design will be more improve

muhangi elioda
muhangi elioda
7 months ago

hey Bin ..what do you mean by design will ne more improve..?

nanakweku
nanakweku
10 months ago

Thanks. Quick solution

Related Articles