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.
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.
Start from behaviour, not looks. Does the user have to deal with it before doing anything else?
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::backdropbehind it, everything outside becomes inert (cannot be clicked, focused or found by screen readers), focus moves inside (to the element withautofocus, 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.
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().
showModal() sits inside a card with overflow: hidden and z-index: 1. A sticky header has z-index: 9999. What do you see?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 aspopover="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".
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.
command | Target | Does |
|---|---|---|
show-modal | dialog | showModal() |
close | dialog | close(), with the button's value as returnValue |
request-close | dialog | requestClose(), so cancel fires first |
toggle-popover, show-popover, hide-popover | popover | the matching method |
--anything | any element | fires a command event you handle yourself |
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 each piece of UI to the best native primitive.
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-nameon the trigger gives it a name that starts with two dashes.position-anchoron the positioned element picks that anchor.position-areaplaces the element in a 3 by 3 grid around the anchor:top,bottom right,left center,bottom span-rightand 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-fallbackslists alternatives the browser tries if the element would overflow:flip-block(above becomes below),flip-inline(left becomes right), both, or position areas such asbottom.
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.
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-stylegives the values the element starts from on its first frame after it appears, so it can transition in.transition-behavior: allow-discreteletsdisplayandoverlay(the property that keeps the element in the top layer) wait until the exit transition finishes, so it can transition out.
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.
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; }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>
The accessibility checklist
Native elements get most behaviour right, but not everything:
- Name every dialog. Point
aria-labelledbyat its heading, or usearia-label. An unnamed dialog is announced as just "dialog". - Pick the first focus deliberately.
autofocuson the least destructive action, or on the first field of a form. For a long dialog, focus the heading (withtabindex="-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-hiddenor manual focus traps withshowModal(). 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.
aria-hidden="true" to main and a JavaScript focus trap when opening a dialog with showModal(). What is the best review comment?- 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.