Skip to content

Lesson 24 of 52Modern CSS

Dialogs, Popovers and Anchored UI Without a Library

Build modals, menus, toasts and tooltips with dialog, popover, invoker commands and anchor positioning, with focus, Escape and stacking handled for you.

19 min read0/4 questions

Every product has the same handful of floating UI: a confirm dialog, an account menu, a toast, a tooltip, a date picker. For years each one meant a library or a few hundred lines of JavaScript to handle focus, the Escape key, clicks outside, z-index wars and keeping the thing on screen near its button. Most of that is now built into HTML and CSS. In Positioning you built a modal overlay by hand with position: fixed and a z-index; this lesson replaces it with native dialog, the popover attribute, invoker commands that open both with no script, CSS anchor positioning for tooltips and menus, and entry and exit animations for all of them. Knowing exactly what the platform gives you, and where it still has gaps, is what lets you delete code instead of adding it.

The top layer

Native dialogs and popovers share one idea that solves the z-index problem for good. When you open them they move into the top layer: a separate layer the browser paints above the entire document. Nothing on the page can sit above it, however high its z-index, and an ancestor with overflow: hidden or a transform cannot clip it. Elements in the top layer stack in the order they were opened, so a confirm dialog opened from a menu sits above the menu.

Pick the right primitive
Floating UI: what do you need?Floating UIwhat do you need?dialog + showModal(): blocks the pagedialog + showModal()blocks the pagepopover (auto): one at a time, light dismisspopover (auto)one at a time, light dismisspopover=manual: you close itpopover=manualyou close itanchor positioning: place it by a buttonanchor positioningplace it by a buttonmust answer firstmenu, pickertoast, persistentposition it

Start from behaviour, not looks. Does the user have to deal with it before doing anything else?

1/5

dialog: modal and non-modal

<dialog> has been in every major browser since 2022. It has two ways to open, and they behave very differently:

  • dialog.showModal() opens it modally. It goes into the top layer, the browser draws a ::backdrop behind it, everything outside becomes inert (cannot be clicked, focused or found by screen readers), focus moves inside (to the element with autofocus, otherwise the first focusable element), and Escape closes it.
  • dialog.show() opens it non-modally, in normal flow with no backdrop, no inertness and no Escape handling. This is rarely what you want; a popover is usually better for non-blocking UI.

When it closes, browsers return focus to the element that was focused before it opened, which is normally your trigger button. Test it anyway, especially if the trigger can disappear (deleting a row from a menu inside that row), because then you must move focus somewhere sensible yourself.

A form inside a dialog can use method="dialog". Submitting it closes the dialog with no network request and sets dialog.returnValue to the value of the button that was pressed. That gives you a confirm prompt with almost no code.

HTML & CSS
<style> dialog { border: 0; border-radius: 12px; padding: 20px; max-width: 320px; box-shadow: 0 20px 40px rgb(0 0 0 / 0.25); } dialog::backdrop { background: rgb(15 23 42 / 0.6); } .actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; } button { font: inherit; padding: 6px 12px; } .danger { background: #b91c1c; color: white; border: 0; border-radius: 6px; } html:has(dialog:modal) { overflow: hidden; }</style><p>Project "Atlas" has 14 files.</p><button id="open">Delete project</button><p id="log">Nothing chosen yet.</p> <dialog id="confirm" aria-labelledby="confirm-title"> <h2 id="confirm-title">Delete Atlas?</h2> <p>This removes all 14 files. You cannot undo it.</p> <form method="dialog" class="actions"> <button value="cancel" autofocus>Cancel</button> <button value="delete" class="danger">Delete</button> </form></dialog> <script> const dialog = document.getElementById("confirm"); document.getElementById("open").addEventListener("click", () => { dialog.returnValue = ""; dialog.showModal(); }); dialog.addEventListener("close", () => { document.getElementById("log").textContent = "returnValue: " + (dialog.returnValue || "(Escape pressed)"); });</script>

Preview

Open it and try every way out: Cancel, Delete and Escape. Tab cycles through the dialog's buttons and never reaches the page behind it (on a real page it may also visit the browser's own toolbar, which is expected, and in this preview it can step out to the lesson around it). Focus starts on Cancel (because of autofocus, the safe default for destructive actions), and focus goes back to "Delete project" afterwards. The html:has(dialog:modal) rule stops the page behind from scrolling, which the dialog does not do by itself.

The events are worth knowing. Escape fires cancel first, then close. You can call preventDefault() on cancel to keep a dialog open (for example if a form has unsaved changes), but browsers limit how often a page can block Escape without the user interacting, so it cannot be used to trap people. dialog.requestClose() closes a dialog the way Escape does, firing cancel so your checks run, while dialog.close(value) closes it straight away.

Light dismiss and closedby

Clicking the backdrop does not close a modal dialog by default. The closedby attribute controls this: closedby="any" allows clicking outside, Escape and your own buttons; closerequest (the default for modal dialogs) allows Escape and your buttons; none allows only your buttons. As of late 2026 it works in Chrome, Edge and Firefox but not yet in Safari, so add a fallback. A click on the backdrop is reported with the dialog itself as the target, which makes the fallback short:

dialog.addEventListener("click", (event) => {
  if (event.target === dialog) dialog.requestClose();
});

This only works if the dialog's content fills it with no padding gap, so put the padding on an inner wrapper, or check the click coordinates against dialog.getBoundingClientRect().

Quick check
A modal opened with showModal() sits inside a card with overflow: hidden and z-index: 1. A sticky header has z-index: 9999. What do you see?
Need a nudge? A hint rules out a wrong answer.

The popover attribute

Add popover to any element and it becomes hidden until opened, then shows in the top layer. A button with popovertarget pointing at its id toggles it. No JavaScript. Popover has been Baseline in all major browsers since early 2025.

A popover is not modal. The page stays interactive, focus does not move, and screen readers can still reach everything. That makes it right for menus, pickers, toasts and "more info" panels, and wrong for anything the user must answer.

  • popover (the same as popover="auto"): light dismiss. Clicking outside or pressing Escape closes it, and opening one auto popover closes any other that is not its ancestor, so only one menu is open at a time. Nested popovers (a submenu inside a menu) stay open together.
  • popover="manual": no light dismiss and no auto-closing of others. It stays until you hide it. Use it for toasts and anything several of which can be open at once.
  • popover="hint": a newer value for tooltips, which closes other hints but not auto popovers. Chrome and Firefox support it; Safari does not yet, so check support before using it.

The invoking button gets the right accessibility for free: browsers expose it as expanded or collapsed and link it to the popover. After you open a popover from a button, the next Tab moves into the popover even if it is far away in the source.

In JavaScript, el.showPopover(), el.hidePopover() and el.togglePopover() control it, the :popover-open pseudo-class styles the open state, and the beforetoggle and toggle events report event.newState as "open" or "closed".

HTML & CSS
<style> [popover] { margin: 0; border: 1px solid #cbd5e1; border-radius: 10px; padding: 6px; } .menu { inset: auto; top: 60px; left: 16px; } .menu a { display: block; padding: 6px 12px; color: #0f172a; text-decoration: none; border-radius: 6px; } .menu a:hover, .menu a:focus-visible { background: #e2e8f0; } .toast { inset: auto 16px 16px auto; background: #14532d; color: white; border: 0; padding: 10px 14px; } button { font: inherit; padding: 6px 12px; }</style><button popovertarget="account">Account</button><button id="save">Save</button> <div id="account" popover class="menu"> <a href="#profile">Profile</a> <a href="#billing">Billing</a> <a href="#signout">Sign out</a></div> <div id="toast" popover="manual" class="toast" role="status">Saved</div> <script> const toast = document.getElementById("toast"); let timer; document.getElementById("save").addEventListener("click", () => { toast.showPopover(); clearTimeout(timer); timer = setTimeout(() => toast.hidePopover(), 2500); });</script>

Preview

Open the account menu, then click anywhere else or press Escape: it closes. Now open the menu and click Save: that click lands outside the menu, so light dismiss closes the menu, while the toast appears and ignores later clicks elsewhere, because manual popovers have no light dismiss. It hides only when the timer calls hidePopover(). Note margin: 0 and inset: auto: the browser's default popover styles centre it with inset: 0; margin: auto, so you reset them when you position it yourself.

The account menu here is a list of links, not role="menu". That is deliberate. ARIA menus are for application-style menus with arrow-key navigation, and making site navigation into one adds keyboard rules users do not expect. A popover full of links is a disclosure, which is exactly what ARIA Widget Patterns recommends for most "menus" on websites.

Invoker commands: dialogs with no JavaScript

popovertarget only opens popovers. Invoker commands generalise it to dialogs: a button with commandfor naming the target's id and command naming the action. They became Baseline in December 2025 when Safari 26.2 shipped them.

commandTargetDoes
show-modaldialogshowModal()
closedialogclose(), with the button's value as returnValue
request-closedialogrequestClose(), so cancel fires first
toggle-popover, show-popover, hide-popoverpopoverthe matching method
--anythingany elementfires a command event you handle yourself
HTML & CSS
<style> dialog { border: 0; border-radius: 12px; padding: 20px; max-width: 300px; } dialog::backdrop { background: rgb(0 0 0 / 0.5); } button { font: inherit; padding: 6px 12px; } #count { font-weight: bold; }</style><button commandfor="news" command="show-modal">Subscribe</button><p>Copies: <span id="count">1</span> <button commandfor="count" command="--add">Add one</button></p> <dialog id="news" aria-labelledby="news-title"> <h2 id="news-title">Weekly digest</h2> <p>One email every Friday. Unsubscribe any time.</p> <button commandfor="news" command="close" value="no">Not now</button> <button commandfor="news" command="close" value="yes">Subscribe</button></dialog> <script> const count = document.getElementById("count"); count.addEventListener("command", (event) => { if (event.command === "--add") count.textContent = Number(count.textContent) + 1; });</script>

Preview

The dialog opens and closes with no script at all. The custom --add command shows the pattern for your own actions: the target gets a command event with event.command and event.source (the button), so one listener on the target replaces a click handler on every button. Custom commands must start with two dashes. In an older browser the buttons simply do nothing, so for a must-work feature keep a small script fallback, or feature detect with "command" in HTMLButtonElement.prototype.

Match the pairs0/5 matched

Match each piece of UI to the best native primitive.

Choose an item, then its match on the other side.

Anchor positioning

A menu or tooltip needs to sit next to its button and stay on screen. Before, that meant measuring with getBoundingClientRect() on every scroll and resize, or a library such as Floating UI. CSS anchor positioning does it in the browser. The core features reached all three engines when Firefox 147 shipped in January 2026; some newer details still differ, so test in each browser.

.trigger { anchor-name: --help; }
 
.tip {
  position: absolute;          /* or fixed */
  position-anchor: --help;     /* which anchor to use */
  position-area: top;          /* sit above it, centred */
  margin-bottom: 6px;
  position-try-fallbacks: flip-block;   /* no room above? go below */
}
  • anchor-name on the trigger gives it a name that starts with two dashes.
  • position-anchor on the positioned element picks that anchor.
  • position-area places the element in a 3 by 3 grid around the anchor: top, bottom right, left center, bottom span-right and so on. It covers most needs in one line.
  • For exact control, use the anchor() function inside inset properties: top: anchor(bottom); left: anchor(left); means "my top edge at the anchor's bottom edge". anchor-size(width) lets a dropdown match its button's width.
  • position-try-fallbacks lists alternatives the browser tries if the element would overflow: flip-block (above becomes below), flip-inline (left becomes right), both, or position areas such as bottom.

Popovers give you one more shortcut. A popover opened by a button through popovertarget or commandfor gets that button as an implicit anchor, so you can use position-area without naming anything. This is handy when a list renders twenty identical buttons.

HTML & CSS
<style> body { height: 600px; } .row { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 90px; } button { font: inherit; padding: 6px 12px; } [popover] { margin: 6px; inset: auto; position-area: top; position-try-fallbacks: flip-block; width: max-content; max-width: 200px; padding: 6px 10px; border: 0; border-radius: 6px; background: #0f172a; color: white; font-size: 13px; }</style><p>Scroll the preview so the buttons reach the top edge, then open a tip again.</p><div class="row"> <button popovertarget="t1">Plan</button> <button popovertarget="t2">Seats</button> <button popovertarget="t3">Billing</button></div><div id="t1" popover>Your plan renews on the 1st.</div><div id="t2" popover>3 of 5 seats used.</div><div id="t3" popover>Invoices are emailed to the account owner.</div>

Preview

Each popover sits above its own button with no names and no script. Scroll down until the buttons are near the top of the preview and open one again: there is no room above, so it flips below. Change top to right and flip-block to flip-inline to make side tooltips.

A tooltip shown on hover and focus has its own rules: WCAG 1.4.13 requires that it can be dismissed without moving the pointer (Escape), that the pointer can move onto it without it vanishing, and that it stays until the user moves away. A click-to-open popover, as above, meets these easily. Pure hover tooltips do not, and they never work on touch screens. Never put essential information only in a tooltip.

Animating in and out of the top layer

Dialogs and popovers switch between display: none and visible, which normally cannot be animated. Two features from Transitions and Animations' toolbox make it work:

  • @starting-style gives the values the element starts from on its first frame after it appears, so it can transition in.
  • transition-behavior: allow-discrete lets display and overlay (the property that keeps the element in the top layer) wait until the exit transition finishes, so it can transition out.
HTML & CSS
<style> dialog, [popover] { opacity: 1; transform: none; transition: opacity 200ms ease-out, transform 200ms ease-out, display 200ms allow-discrete, overlay 200ms allow-discrete; } @starting-style { dialog[open], [popover]:popover-open { opacity: 0; transform: translateY(12px); } } dialog:not([open]), [popover]:not(:popover-open) { opacity: 0; transform: translateY(12px); } dialog::backdrop { background: rgb(0 0 0 / 0.5); transition: opacity 200ms, display 200ms allow-discrete, overlay 200ms allow-discrete; } @starting-style { dialog[open]::backdrop { opacity: 0; } } dialog:not([open])::backdrop { opacity: 0; } @media (prefers-reduced-motion: reduce) { dialog, [popover], dialog::backdrop { transition: none; } } dialog { border: 0; border-radius: 12px; padding: 20px; } button { font: inherit; padding: 6px 12px; }</style><button commandfor="d" command="show-modal">Open dialog</button><button popovertarget="p">Open popover</button><dialog id="d" aria-label="Example"> <p>I fade and slide in and out.</p> <button commandfor="d" command="close">Close</button></dialog><div id="p" popover>So do I.</div>

Preview

Open and close both. Three states matter: the open state (fully visible), the @starting-style state (where it comes in from), and the closed state (where it goes back to). Entries animate in every current browser. Exits run fully in Chrome and Edge; Firefox does not yet transition display, and only Chromium supports overlay, so in Firefox and Safari the exit is currently instant. That is the right failure: the UI still works, only the polish is missing.

Exclusive accordions and customisable select

Two smaller features complete the set.

Give several details elements the same name and opening one closes the others, like radio buttons. It has been Baseline since 2024 and needs no script.

HTML & CSS
<style> details { border: 1px solid #cbd5e1; border-radius: 8px; padding: 8px 12px; margin-bottom: 6px; } summary { cursor: pointer; font-weight: 600; }</style><details name="faq" open><summary>Can I cancel?</summary><p>Yes, any time from Billing.</p></details><details name="faq"><summary>Do you offer refunds?</summary><p>Within 14 days of purchase.</p></details><details name="faq"><summary>Is there a student plan?</summary><p>Yes, with a valid student email.</p></details>

Preview

One warning: users cannot search inside a closed exclusive section and compare two answers side by side, so use it when it really helps, not by default.

Customisable select lets you style a real select and its dropdown: opt in with appearance: base-select on both select and ::picker(select), and you can put markup (icons, two-line options) inside option elements and a selectedcontent element shows the chosen option in the button. It ships in Chrome and Edge (135 and later) and Safari 27, and is behind a flag in Firefox as of late 2026. Treat it as progressive enhancement: in other browsers the same markup renders as an ordinary, fully working select. That is far safer than a custom div dropdown, which loses keyboard support, form submission and mobile pickers.

select, ::picker(select) { appearance: base-select; }
select::picker-icon { display: none; }
option:checked { font-weight: 600; }
Predict the outputHTML

The user opens the Filters popover, then opens the Sort popover, then clicks the Save button (which shows the toast). How many of the three popovers are open now? Type a number.

<div id="filters" popover>...</div>
<div id="sort" popover>...</div>
<div id="toast" popover="manual">Saved</div>
Need a nudge? Hints walk you through it.

The accessibility checklist

Native elements get most behaviour right, but not everything:

  • Name every dialog. Point aria-labelledby at its heading, or use aria-label. An unnamed dialog is announced as just "dialog".
  • Pick the first focus deliberately. autofocus on the least destructive action, or on the first field of a form. For a long dialog, focus the heading (with tabindex="-1") so the user hears it from the top.
  • Restore focus to the trigger, and handle the case where the trigger no longer exists.
  • Do not use aria-hidden or manual focus traps with showModal(). The browser already makes the rest of the page inert; extra code usually breaks it.
  • Popovers are not modal. If users must not interact with the page underneath, you need a dialog.
  • Tooltips must be dismissible with Escape, hoverable and persistent (1.4.13), and must not hold essential content.
  • Respect reduced motion for every entry and exit animation.
Quick check
A developer adds aria-hidden="true" to main and a JavaScript focus trap when opening a dialog with showModal(). What is the best review comment?
Need a nudge? A hint rules out a wrong answer.
Key terms
top layer
A browser layer painted above the whole document, where modal dialogs and open popovers live, unaffected by z-index or overflow.
inert
The state of content that cannot be focused, clicked or reached by assistive technology; a modal dialog makes the rest of the page inert.
light dismiss
Closing a popover or dialog by clicking outside it or pressing Escape.
popover
An HTML attribute that turns any element into a non-modal top-layer overlay, with auto, manual and hint modes.
invoker commands
The commandfor and command attributes on a button, which open, close or toggle dialogs and popovers without JavaScript.
anchor positioning
CSS that places an element relative to another element (its anchor) with anchor-name, position-area and anchor(), with fallbacks.
allow-discrete
A transition-behavior value that lets discrete properties such as display and overlay switch at the end of a transition, enabling exit animations.