CSS-Only Dropdown Menu with the Popover API
Dropdown menus without JavaScript toggles
The old way used JS for toggle, click-outside, and ESC, plus manual aria. The popover attribute and popovertarget give you a built-in dismissible popover with no toggle code.
The old hack vs the modern fix
View demo.menu {
display: none;
}
.menu.open {
display: block;
}
/* JS: toggle class, document click-outside, keydown ESC, aria-expanded, aria-hidden *//* <button id="menu-button" popovertarget="menu"> ... <div id="menu" popover> */
#menu-button {
anchor-name: --menu;
}
#menu[popover] {
position: absolute;
position-anchor: --menu;
position-area: bottom span-right;
inset: auto;
margin: 0.25rem 0 0;
}
/* Toggle, light dismiss, ESC: built in. */Popover browser support
The Baseline label is for popover. Anchor positioning, which places the menu under its button, works in Chrome and Edge 129, Firefox 147 and Safari 26, but it is not Baseline yet. Without it, the menu still opens, closes and light-dismisses. It just isn't placed under the button.
Live demo
Why the modern way wins
Built-in toggle
Click the button to open, click outside or press ESC to close. No event listeners.
Top layer
Popover goes in the top layer. No z-index fights with the rest of the page.
Accessible
The platform handles focus and dismiss. You style the popover and wire the button with popovertarget.
- Lines Saved
- 12+ → 5
- No toggle or dismiss JS
- Old Approach
- JS toggle + aria
- Click-outside, ESC, aria-expanded
- Modern Approach
- popover + popovertarget
- Light dismiss, ESC, top layer
How it works
The old way: a click handler toggles a class that shows or hides the menu. You add a document click listener for click-outside, a keydown listener for Escape, and you manage aria-expanded and aria-hidden yourself. It's easy to miss an edge case.
The modern way: put popover on the menu element and popovertarget="menu" on the button. The button becomes a popover trigger. Opening, closing, click-outside, and ESC are built in. The menu is rendered in the top layer. You only need CSS to position and style it.
A popover opens centered in the viewport by default, because the browser gives it inset: 0 and margin: auto. Anchor positioning pins it under its button instead: anchor-name on the button, then position-anchor and position-area: bottom span-right on the menu, with inset: auto to clear the default. Browsers without anchor positioning ignore those lines and still open, close and light-dismiss the menu.
role="menu" to the popover and role="menuitem" to each option. Arrow key navigation between menu items still requires JavaScript.