Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSSWeb Platform

Build a dropdown with the popover attribute

Use popover and popovertarget to build an account menu that opens, closes on Escape or an outside click, and needs no JavaScript.

Use an HTML popover to open a list of account links from a button. The browser handles toggling the list and closing it on Escape or an outside click.

Markup

Give the menu popover and point a button at it with popovertarget. The value of popovertarget is the id of the menu.

<header>
  <button type="button" popovertarget="account-menu">Account</button>
  <ul id="account-menu" popover>
    <li><a href="/profile">Profile</a></li>
    <li><a href="/billing">Billing</a></li>
    <li><a href="/settings">Settings</a></li>
  </ul>
</header>

Click Account and the list appears on top of the page. The browser puts the open popover in the top layer above ordinary page content.

Click the button again and it hides. Until then the list is display: none, so you do not need a hidden class.

Position it

A popover opens in the middle of the viewport. The browser's default style is position: fixed with inset: 0 and margin: auto.

Put this rule in your stylesheet. It resets inset, then places the list under the button with top and right.

#account-menu {
  inset: unset;
  top: 3.5rem;
  right: 1rem;
  margin: 0;
  padding: 0.5rem 1rem;
  list-style: none;
}

In my test page the list opens 56 px from the top and 16 px from the right edge. Those offsets suit that header, so change them to suit yours. These fixed offsets use the viewport as their reference. Adjust them if the header height changes.

What you get without JavaScript

The menu closes when you press Escape, and it closes when you click anywhere outside it. MDN calls this light dismiss. It applies to a popover set with popover or popover="auto", which is the same thing.

Opening another auto popover closes this one unless the new popover is nested in it.

Focus is handled too. After you open the menu, Tab moves to the first link inside it. Press Escape from a link inside the popover to close it and return focus to the Account button.

The popovertarget relationship gives the button an implicit expanded state. Keep the list as regular navigation links so Tab moves through them.

If you want a panel that stays open until the user closes it, write popover="manual". A manual popover cannot be light dismissed, and its buttons still show and hide it. I use manual for panels such as help text and the default for menus.