
♪ I Was Made For Lovin' Accordions
Mastering the HTML <details>
element is a skill every frontend developer should have in their toolkit. In this guide, we’ll expand (pun intended!) on what <details>
can do—showing you how to move beyond simple toggles and use it as the foundation for more complex layouts like site navigation megamenus and dropdowns.
Raw HTML#
Here’s a quick example using just <details> and <summary>. No CSS, no JavaScript—just the barebones HTML in action.
Pro tip: adding a name
attribute will link the details elements together, allowing only one to be expanded at a time.
Basic Styling#
Now let's add some Tailwind to style the details elements like a navigation menu. I'm going with a full-width megamenu layout, and a compact version with a dropdown style.
Pro tip: use the [open]
selector to style the <summary>
's open state indicator (i.e. the "+" and "-").
Toggling State with Hover#
I wrote some vanilla JavaScript so that <details>
elements can open on hover (desktop only) and on tap (mobile). This way, users don’t have to explicitly click the disclosure arrow if they’re browsing with a mouse, but mobile users still get the familiar tap-to-toggle behavior.
Pro tip: Use window.matchMedia
to detect whether the device supports hover. Then, I added or removed the appropriate event listeners (mouseenter
/ mouseleave
for desktop, click
for mobile).
Adding Hover Safe Areas#
In the previous example, try moving your mouse from "Megamenu #1" directly to "💧 Squirtle". You may notice a frustrating UX problem: Megamenu #2 opens unintentionally while you’re crossing over.
To fix this, I created a new utility class that can be added to a <details>
element in the megamenu. This class uses a triangular-shaped pseudo-element (shown here with a green background for clarity) that expands the “safe area.”
The safe area acts as a hover buffer, allowing the user to move the mouse diagonally without accidentally triggering a different menu.
Conclusion#
This is only scratching the surface of what you can build with the powerful <details>
element. From simple toggles to nested accordions, hover states, and even custom-styled interactions, it gives you a ton of flexibility with minimal markup.
You can explore all of the live CodePen examples referenced in this article here.
