Dropdown Menu Component
Create a positioned dropdown menu that appears below a trigger button using absolute positioning, shadow, and rounded corners.
What Is a Dropdown Menu
A dropdown menu is a panel of options that appears below (or beside) a trigger element when activated. Unlike a native <select>, a custom dropdown can contain icons, descriptions, badges, dividers, and any other HTML content.
The key challenge with dropdowns is positioning: the panel must appear directly below the trigger and stay within the viewport. Tailwind's positioning utilities combined with a small amount of JavaScript make this achievable without any external library.
Trigger Button Structure
The dropdown trigger is usually a button that shows the currently selected option or an action label. Wrap the trigger and the dropdown panel together in a relative container so the panel positions itself relative to the trigger.
The trigger button uses inline-flex items-center gap-2 to align a label and a chevron icon. The chevron can rotate with rotate-180 when the dropdown is open to indicate state.
<div class="relative inline-block">
<button
id="dd-trigger"
onclick="toggleDropdown()"
class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium
text-gray-700 bg-white border border-gray-300 rounded-lg
hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
Options
<svg id="dd-chevron" class="w-4 h-4 transition-transform duration-200"
fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
</svg>
</button>
</div>All lessons in this course
- Modal Dialog Structure
- Modal Open and Close Animation
- Dropdown Menu Component
- Accessible Modals and Dropdowns