Design System

Design System

Modal Dialog

Surfaces

Open in Storybook: Modal Dialog (opens in a new tab)

On this page

Overview

A native dialog for a modal that stops the page and waits for an answer the person just asked for. The browser makes the page behind it inert, draws the backdrop, closes on Esc and returns focus to the opener. It also draws a drawer beside the page.

The component adds the heading that names it, a 44 × 44 Close button, declared initial focus and a custom focus trap. That one is my choice, and it is explained under Focus trap.

Modal only: non-modal dialogs, popovers, toasts and banners are not covered.

Anatomy

  1. Opener

    button command="show-modal" commandfor

    Opens with no JS. Focus returns to it from every exit.

  2. Dialog

    dialog closedby

    Top layer, inert page, Esc.

  3. Name

    h2 + aria-labelledby

    Heard as “Delete this draft?, dialog”.

  4. Close button

    button command="close" aria-label="Close"

    Only when leaving costs nothing.

  5. Description

    p + aria-describedby

    What happens, how to leave.

  6. Actions

    button in form method="dialog"

    Named by action: “Delete draft”, never “OK”.

  7. Backdrop

    ::backdrop

    Dims the page. inert does the work.

Usage

Variants

alertdialog only when the answer is required to finish what was just started. If the flow can go on without it, a dialog: one attribute apart.

  • Confirm a destructive action

    Buttons named by action: “Delete draft”, never “OK”.

    closedby="any" · initialFocus

    Focus lands on Cancel.

    Delete this draft?

    “Spring menu” and its 3 photos will be deleted. You can’t undo this.

  • Unsaved changes

    Two labelled exits and no Close. The safe one keeps the work.

    role="alertdialog" · closedby="none" · showCloseButton={false}

    Focus lands on Keep editing.

    Leave without saving?

    Your changes to “Spring menu” will be lost.

  • Critical failure

    Retry runs inside and doesn’t close. After the last attempt only Work offline is left.

    role="alertdialog" · closedby="none"

    Focus lands on Retry.

    Couldn’t send your order

    The connection dropped. Your order is still here.

  • Permission pre-prompt

    Say what, why, where it stays and what happens if no. The browser prompt comes from Allow.

    role="alertdialog"

    Focus lands on Not now.

    Use your location?

    To show boutiques near you. It stays on this device. Without it, you can search by city.

  • Terms or consent gate

    No Close button. The terms scroll by keyboard.

    role="alertdialog" · closedby="none" · showCloseButton={false}

    Focus lands on Decline.

    Accept the updated terms

    Read the changes before you continue.

    1. What changed. We now store your order history for 24 months, so you can repeat an order in one step.

    2. Your rights. You can ask for a copy or deletion at any time, from your account or by writing to us.

    3. Cookies. Only the ones that keep you signed in are set until you choose.

  • Progress that must finish

    No exit while it runs. Close appears when it is done.

    closedby none, then closerequest

    Focus lands on the heading.

    Uploading 3 photos

    0 of 3 uploaded

  • Settings, picker, form

    Cancel is formnovalidate: a required field blocks Save, never an exit.

    closedby="closerequest"

    Focus lands on the heading.

    Delivery address

    Example: Via Roma 12

    Example: Monza

  • Media viewer

    Named by its caption. Close is the only chrome, so touch, voice and switch users have an exit.

    ariaLabelledBy · initialFocus="[data-media]"

    Focus lands on the media.

    Ristretto capsule, top view

    Esc to close

  • Drawer: filters, history

    The same dialog beside the page, with the same head, exits and focus.

    variant="drawer" · position

    Focus lands on the heading.

    Filters

    Size · Roast · Intensity

Props

Props
PropDoesDefault
idRequired. The opener’s commandfor points to it—
titleNames the dialog: its h2 is what aria-labelledby points to and what takes focus on open—
ariaLabelledBy, ariaLabelName it when there is no title—
aria-describedbyNames the paragraph that says what happens or how to leave—
rolealertdialog only when the answer is required to finish what was just starteddialog
closedbyany: Esc and a click on the backdrop. closerequest: Esc only. none: an answer is required, and the content owes labelled exitsany
showCloseButton, closeLabelThe 44 × 44 Close button and its nametrue, Close dialog
initialFocusA selector for the element that takes focus on open, such as the safe button of an alertdialog. Never CloseThe heading, or an element with autofocus
open, onClose(returnValue)Control it from state. Without open, a button with command="show-modal" and commandfor opens it, with no script—
variant, positiondrawer slides in from left, right, bottom or left-bottommodal, right
restoreFocusRefThe element that takes focus on close instead of the openerThe opener
ModalDialogButton · kindprimary is the answer, secondary the way out, danger an answer that destroys. 47px tall, never under 44pxsecondary

Example

A button opens it with the invoker command, no script. Each button of the form gives its value as the returnValue that onClose receives.

import { ModalDialog } from '@/components/ModalDialog'

<button type="button" {...{ command: 'show-modal', commandfor: 'del' }}>
  Delete draft
</button>

<ModalDialog
  id="del"
  title="Delete this draft?"
  onClose={(answer) => answer === 'delete' && removeDraft()}
>
  <p>“Spring menu” and its 3 photos will be deleted.</p>
  <form method="dialog">
    <button value="cancel">Cancel</button>
    <button value="delete">Delete draft</button>
  </form>
</ModalDialog>

Specs

Measurements

Measurements
PartPropertyValue
PanelWidthmax-inline-size: 32rem, centred. 480px in the design
PanelPadding · gap24px · 12px
HeaderHeight · gap44px · 12px
TitleTextWork Sans bold, 20px / 120%
DescriptionTextWork Sans regular, 15px / 145%
ActionsGap12px
Close buttonSize · corner44 × 44px · 8px
Close buttonGlyph18px, 3px stroke, aria-hidden
ButtonSize47px tall, padding 11px 20px. 44px minimum
ButtonCorner · border6px · 1.5px
ButtonLabelWork Sans bold, 15px / 145%
Focus ringWidth · gap3px · 3px off the button. Close draws it inside its 44px. On buttons, Close and the heading
MotionDuration0.2s, opacity and translate of 1rem. 1ms under reduced motion

Adapting to viewports

The panel shrinks to the viewport, then fills it and scrolls inside. Close and the actions stay reachable; the page behind never scrolls. Each variant is a story in Storybook. Pick the width in the viewport menu of the toolbar, for any story: 640 CSS px · 200% zoom, 390 · mobile or 320 CSS px · 400% zoom.

Adapting to viewports
WidthPanelWhat changes
1280 CSS px · 100%Centred, max-inline-size: 32remBackdrop over the inert page; scroll locked
640 CSS px · 200%Full width minus 1remButtons stay side by side if they fit
390 · mobileFull width minus 1rem, max-block-size: 100dvh − 2remButtons stack, the safe one first. A visible Close: touch has no Esc
320 CSS px · 400% (1.4.10)Fullscreen: inset: 0; margin: 0; 100dvhThe panel scrolls inside; a scrolling region with no control has tabindex="0"
Text 200% (1.4.4)Height from contentHeading and buttons wrap; nothing is clipped by a fixed height

Motion

Animate in and out without breaking the exit or reduced motion.

dialog[open] { display: grid; }          /* display only when open */
dialog, dialog::backdrop {
  transition: opacity .2s, translate .2s, overlay .2s allow-discrete, display .2s allow-discrete;
}
dialog:not([open]) { opacity: 0; translate: 0 1rem; }
@starting-style { dialog[open] { opacity: 0; translate: 0 1rem; } }

@media (prefers-reduced-motion: reduce) {
  dialog, dialog::backdrop {
    transition: opacity 1ms, overlay 1ms allow-discrete, display 1ms allow-discrete;   /* keep display and overlay */
    translate: none;
  }
}

Markup

<button command="show-modal" commandfor="del" id="opener">Delete draft</button>

<dialog id="del" closedby="any" aria-labelledby="del-h" aria-describedby="del-d">
  <h2 id="del-h">Delete this draft?</h2>
  <p id="del-d">“Spring menu” and its 3 photos will be deleted. You can’t undo this.</p>
  <form method="dialog">
    <button value="cancel" autofocus>Cancel</button>
    <button value="delete">Delete draft</button>
  </form>
</dialog>

Script

HTML first, then the script for what native does not do: the opener when a key or state opens it, the Tab wrap (a custom focus trap), the cancel guard and returnValue.

const dialog = document.getElementById('del')
const leave = document.getElementById('leave')    // the sibling alertdialog
let dirty = false
let opener                                        // only when a key or state opens it

const open = () => { opener = document.activeElement; dialog.showModal() }

// Tab wrap, a custom focus trap: wrap only, nothing more
dialog.addEventListener('keydown', (e) => {
  if (e.key !== 'Tab' || e.target.matches('video, audio')) return
  const f = [...dialog.querySelectorAll('button, input, select, textarea, a[href], [tabindex="0"]')]
    .filter((el) => !el.disabled)
  if (e.shiftKey && e.target === f[0]) { e.preventDefault(); f.at(-1).focus() }
  else if (!e.shiftKey && e.target === f.at(-1)) { e.preventDefault(); f[0].focus() }
})

// Guard: ask once, in a sibling dialog. Close calls the same guard.
const guard = (e) => { if (dirty) { e.preventDefault(); leave.showModal() } }
dialog.addEventListener('cancel', guard)
dialog.addEventListener('command', (e) => e.command === 'close' && guard(e))

dialog.addEventListener('close', () => {
  if (dialog.returnValue === 'delete') removeDraft()   // the exact word
  opener?.focus()
})

Tokens

Component tokens

The values of the Figma components Dialog / Button and Dialog / Close button.

Component tokens
PartPropertyTokenValue
PanelFillwhite#ffffff
PanelCorner—12px (radius is 8px)
PanelShadow—0 12px 32px, 25% black
BackdropColourink at 55%rgb(22 22 26 / .55)
TitleColourink#16161a
DescriptionColourink-soft#4b4b55
Close glyphColourink#16161a
Close buttonFillwhite#ffffff
Close buttonCornerradius8px
Button, primaryFill and borderlilac#5e548e
Button, primaryLabelwhite#ffffff
Button, secondaryFillwhite#ffffff
Button, secondaryBorder and labelink#16161a
Button, dangerFill and border—#c8102e (danger is #82002a)
Button, dangerLabelwhite#ffffff
Focus ringColourink#16161a, 3px

Guidelines

When to use

  • Use it when the page must stop for an answer the person just asked for.
  • Never on page load or a timer: it steals the caret from someone reading.
  • Don’t ask when nothing changed, or for a choice that can be undone: do it and offer Undo.
  • Extra detail that can sit beside the content is a details or a toggletip.

Ways to open and close

Native first. Script only when state, a key or a promise opens it.

Ways to open and close
WayUse whenNotes
command="show-modal" + commandfor="id" on a buttonDefaultNo JS, focus returns. Fallback: 'command' in HTMLButtonElement.prototype, else a click handler
dialog.showModal()State, a key or a promise opens itSave the opener first
command="close" or dialog.close(value)Cancel buttons, script exitsNever fires cancel, never validates
<form method="dialog"> + submitSubmit is the closereturnValue is the submitter’s value
command event on the dialogGuard a closeevent.command; preventDefault() stops it

closedby

How much it costs to leave decides which exits exist.

closedby
closedbyEscBackdropUse
anyclosesclosesLeaving costs nothing: confirm, picker
closerequestclosesnothingA stray click would lose input; disposable sub-dialogs
nonenothingnothingAnswer required or work in progress. Owes labelled exits

Guarding a close

Guarding a close
RuleHow
Only when closing loses workMulti-step, critical, dirty: preventDefault() on cancel, then ask once in a sibling dialog, with exits named by what they do. Never a handler that keeps refusing
Every exit runs the guardcancel fires on Esc and an any backdrop click, never on close(): the Close button calls the same guard
The safe answerKeeps the work: it gets focus and the primary style
No closedby support'closedBy' in HTMLDialogElement.prototype is false? Also preventDefault() on cancel
Media insidepause() in close, beside the scroll unlock

returnValue

A string, "" at first. close(100) gives "100"; objects go through JSON.stringify and JSON.parse.

returnValue
RuleWhy
Every exit gets its own valueA bare close() and command="close" keep the previous one
Esc and a backdrop clickNot reliable: Chromium clears the value on Esc and keeps the last answer on a backdrop click, WebKit keeps it on Esc (measured). Clear it in the cancel listener: dialog.returnValue = '' The component does it on cancel and on the close command.
Compare the exact word=== 'delete', never if (returnValue): “cancel” is truthy
Read it in closeEvery exit ends there. To await an answer, resolve a promise from a one-time close listener, then showModal(). In React, flushSync state first if the copy depends on the last answer

Forms

A form first: required fields block a submit, never an exit.

Forms
RuleHow
Submit is the close<form method="dialog">. An empty required field blocks it
Cancel, save draftformnovalidate, or a plain-submit Cancel is blocked too. close(), Esc and command="close" skip validation
ErrorsCancel invalid, write the message under the field (aria-describedby, aria-invalid), focus the first failing field
EnterPresses the first submit in the DOM: a left-hand dismiss is type="button"
Must stay openSteps, a result view, a pending send: plain <form onSubmit> + preventDefault(). Only the last step closes natively

Stacked modals

Siblings in the DOM, never nested. Call order is the stack.

Stacked modals
RuleHow
OrderEsc closes the top one; focus returns to the button that opened it; the answer comes back as returnValue on close
Backdrops add upTwo at 0.55 leave about 0.80, and a blur blurs the blur: make the second lighter
Text that changes underneathSaid with its own ariaNotify() call, on that dialog
PopoversOne outside the modal’s subtree is inert while it is open: nest it inside, or close the modal first

Accessibility

Requirements

Requirements
WCAGRequirement
4.1.2 · 2.4.3showModal() or command="show-modal", never the open attribute: that is a non-modal (no top layer, inert, backdrop or Esc)
4.1.2 · 1.3.1Named with aria-labelledby (the heading); aria-label only without one. What happens and how to leave: aria-describedby
4.1.2No tabindex on the dialog. No role="dialog", aria-modal or aria-hidden on the page: native modality covers them
2.1.2Esc closes. closedby="none" owes labelled exits
1.4.10Scroll locked while open and released on every exit: :root:has(dialog:modal) { overflow: hidden; scrollbar-gutter: stable }. A scripted lock is ref-counted
4.1.2 · 2.5.3Close is named “Close” and its glyph is aria-hidden. Buttons say what they do: “Delete draft”, never “OK”. The safe one comes first

Focus management

Focus management
MomentRule
OpenPlaced on every open, never on Close. Declare it with autofocus: no script, no frame to wait for. Undeclared, it lands on the first focusable element, which can be Close. Never in requestAnimationFrame: it doesn’t run in a hidden tab
WhereBy type, see Types. A destructive or consent dialog gets the safe button: Enter on an unread panel must not consent or destroy. Steps: the step heading, on every change of view
ReturnTo the opener from every exit. Invoker commands do it; otherwise save document.activeElement before showModal(). Opened by a key, body is not an opener: save the element, or focus the page heading if it is gone
TrapTab wraps inside the dialog: see Focus trap
ClosedOut of the tab order: display only on dialog[open]. A display: flex on the base rule beats dialog:not([open]) and leaves an invisible form tabbable

Focus trap

Disclaimer: This is MY decision. The dialog tag has a native focus trap, but it considers the interactive UI widgets of the browser, such as its address bar and its toolbar, part of the focus flow. In my opinion this is a blocker for keyboard and screen reader users: if a dialog contains 3 interactive elements, they also have to navigate through the interactive elements of the browser, and their experience gets worse.

I decided to keep the browser interface out of the focus flow, so I implemented a custom focus trap. It is not something the platform asks for: it is mine, and it is the only place in the component that moves focus with a script.

Focus trap
SituationResult
Tab on the last controlGoes to the first control of the dialog, never to the browser interface
Shift+Tab on the first controlGoes to the last control
Ctrl/Cmd+L, F6Still reach the browser interface: no page can block them (whatwg/html#8339)
Focus inside video or audioThe wrap is off: their controls are the browser’s, and it would pin the user on the first control
Any other keyUnchanged. It is a keydown listener on the dialog that does only the wrap, and Esc still closes the dialog when closedby allows

Keyboard

Keyboard
KeyDoes
Tab, Shift+TabMove through the controls inside and wrap: see Focus trap
EscCloses it when closedby allows. Focus returns to the opener
Enter, SpaceOn the opener, opens it. On a button of a form method="dialog", submits and closes

Announcements

A message nothing on the page moves for is said with ariaNotify(), not a live region. The same words are on the page as text. Called once per event, after the focus has moved, on the dialog or an element inside it: a call on the inert page says nothing. Where ariaNotify is missing, nothing is said and nothing replaces it.

Announcements
EventSaid onAnnouncedPriority
An attempt failsThe dialog"Attempt 2 of 3 failed."normal
The last attempt failsThe dialog, after focus moves to Work offline"Attempt 3 of 3 failed. Work offline: your order stays on this device."high: the task stopped and the next step is the person’s
The progress is doneThe progress bar"3 of 3 uploaded. You can close this dialog."normal
Retrying, each photo, openingNot saidThe text is on the page, or focus and the name say it—

WCAG criteria

WCAG criteria
Success criterionLevelMet by
1.3.1 Info and RelationshipsANamed by its heading (aria-labelledby), described by aria-describedby
1.3.2 Meaningful SequenceADOM order = visual order; actions in the order they are read
1.4.3 Contrast (Minimum)AAText in the panel 4.5:1 over the panel, not the backdrop
1.4.4 Resize TextAAPanel height from content; nothing clipped at 200%
1.4.10 ReflowAAFullscreen at 320 px; the panel scrolls inside, the page is locked
1.4.11 Non-text ContrastAAButtons, Close and the focus ring 3:1
2.1.1 KeyboardAEvery exit reachable by keyboard
2.1.2 No Keyboard TrapAEsc, or labelled exits when closedby="none"
2.1.4 Character Key ShortcutsAA one-key opener is switchable, remappable or scoped
2.3.3 Animation from InteractionsAAAprefers-reduced-motion removes translate and scale
2.4.3 Focus OrderAInitial focus placed on every open; focus returns to the opener from every exit
2.4.7 Focus VisibleAA3px ring on heading, buttons and media
2.4.11 Focus Not Obscured (Minimum)AANothing sits over the focused control inside the panel
2.5.8 Target Size (Minimum)AAClose and buttons 44 × 44
3.2.1 On FocusANever opened by focus, a timer or page load
3.3.1 Error IdentificationAForm errors under the field, inside the panel
3.3.4 Error Prevention (Legal, Financial, Data)AAConfirm destructive actions; the safe answer is focused
4.1.2 Name, Role, ValueANative dialog role and modality; alertdialog only when required
4.1.3 Status MessagesAAThe words are on the page as text and ariaNotify() says them from inside the panel

Related

This section is still in progress.

References

This section is still in progress.