Skip to content

Drawer ​

See it live in the styled storefront › — open the ☰ menu at a narrow viewport: the mobile navigation drawer with a drilldown inside.

<pd-drawer> is a thin behavior wrapper around a native <dialog>. The dialog does the heavy lifting — top-layer rendering, background inertness, native focus containment — and pd-drawer adds exactly the things the platform doesn't: a cancelable, animated open/close pipeline, invoker syncing, outside-click, scroll lock, and explicit focus restore.

html
<button commandfor="menu-drawer" command="show-modal">☰ Menu</button>
<pd-drawer>
  <dialog id="menu-drawer" aria-label="Menu">
    <button commandfor="menu-drawer" command="close">✕ Close</button>
    …
  </dialog>
</pd-drawer>

Anatomy ​

html
<!-- 1. Any button anywhere in the document can open the dialog — it targets
        the <dialog>'s id, not pd-drawer's. -->
<button commandfor="menu-drawer" command="show-modal">☰ Menu</button>

<!-- 2. pd-drawer wraps exactly one <dialog> (its first `dialog` descendant).
        pd-drawer itself renders nothing; it's pure behavior. -->
<pd-drawer>
  <!-- 3. The <dialog> is the actual modal surface and the commandfor target. -->
  <dialog id="menu-drawer" aria-label="Menu">
    <!-- 4. Native `close` command — no JS required. -->
    <button commandfor="menu-drawer" command="close">✕ Close</button>

    <!-- 5. Author content: links, forms, or another pd-* component
            (a pd-drilldown or pd-disclosure accordion are the common case —
            see the mobile-menu recipe on the drilldown page). -->
    <nav aria-label="Menu">…</nav>
  </dialog>
</pd-drawer>

Both <pd-drawer> and the <dialog> get an id if the author didn't provide one (pd-drawer-N / pd-drawer-dialog-N) — but invokers, commandfor, and aria-expanded syncing all key off the dialog's id, since that's what show-modal/close/--pd-* commands target.

No <dialog> found? pd-drawer logs one console.warn and skips every dialog-specific effect — no showModal(), no focus management, no scroll lock. The state pipeline itself still runs: show()/hide() never throw, and they still toggle open/data-state on <pd-drawer> and fire the full pd:open/pd:opened/pd:close/pd:closed sequence — so listeners and CSS keyed on the drawer element keep working. A <dialog> appended after connect (e.g. inserted by a framework on next tick) is still picked up, as long as it lands before the drawer's own initialization microtask runs.

What native <dialog> gives you vs. what pd-drawer adds ​

showModal() alone already provides:

  • Top layer rendering — above everything else, no z-index coordination needed.
  • ::backdrop — a stylable pseudo-element behind the dialog.
  • Background inertness — the rest of the page becomes unfocusable/unreachable to assistive tech while the dialog is modal (no manual aria-hidden/inert needed).
  • Native focus containment — Tab/Shift+Tab cycle within the dialog.

pd-drawer adds the parts a modal off-canvas panel needs that the platform doesn't provide:

  • A cancelable, animated open/close pipeline (§3/§4 of the spec) instead of showModal()'s instant, unanimated default — pd:open/pd:close can preventDefault(), and closing waits for your CSS exit animation to finish before dialog.close() actually runs.

  • Invoker sync — aria-expanded kept current on every button[commandfor] targeting the dialog's id, including ones added after connect.

  • Explicit focus save/restore — native dialog focus restore is inconsistent across browsers and polyfills. For command-driven opens the drawer saves the exact CommandEvent.source (important because WebKit can leave pointer-clicked buttons unfocused); API opens fall back to document.activeElement. It restores that target after close settles without yanking focus if you've already moved it elsewhere.

  • Modality-aware initial focus — an [autofocus] inside the dialog always wins. Otherwise a keyboard-driven open (Enter/Space on the invoker) focuses the dialog's first tabbable, or the dialog itself when it has none, so focus never remains behind the modal; a tap/click or programmatic open focuses the dialog element itself (tabindex="-1" is added if absent). The split exists because Safari marks any script-focused element :focus-visible — focusing the close button on tap-open would paint your theme's focus ring uninvited on every tap. Add this one rule to your theme so the (visually meaningless) container ring never shows either:

    css
    dialog:focus-visible,
    pd-drilldown-panel:focus-visible {
      outline: none;
    }
  • Outside-click to close — the native dialog has no built-in "click the backdrop to dismiss"; pd-drawer hit-tests pointerdown coordinates against the dialog's content box.

  • Scroll lock — overflow: clip + scrollbar-gutter: stable on <html> while open (clip removes the scroll container entirely, so the page can't scroll behind the modal even programmatically; the stable gutter prevents layout shift when the scrollbar disappears), re-entrant across stacked drawers.

  • Escape rerouted through the same cancelable/animated path instead of the native instant close.

Attributes ​

All on <pd-drawer>, not the <dialog>.

AttributeTypeDefaultEffect
openboolean (reflected)absentLogical state. Server-rendering it calls showModal() on connect with no events fired (reason 'attribute'). Direct attribute mutation always bypasses pd:open/pd:close cancelation — use show()/hide() for the cancelable path.
close-on-outside-clickmust be the literal string "false" to opt outonA pointerdown on the dialog element itself (i.e. on ::backdrop, hit-tested outside the dialog's content box) closes the drawer with reason 'outside'. Any other value, including an empty attribute, leaves it on — this is a value check, not attribute presence.
scroll-lockmust be the literal string "false" to opt outonSets overflow: clip + scrollbar-gutter: stable on <html> while open. A module-level counter makes it re-entrant: N stacked open drawers lock once, and only the last one closing restores the previous value.

close-on-outside-click and scroll-lock aren't attribute-observed — they're read live at interaction time, so a runtime change takes effect on the very next pointerdown or show() call.

Properties & methods ​

Inherited from the shared open/close pipeline (PdOpenable).

MemberSignatureNotes
openboolean (reflected property)Get/set the open attribute. Setting it bypasses pd:open/pd:close cancelation — the attribute is the source of truth.
show(reason?)(reason?: Reason) => booleanCancelable open. Fires pd:open; if not canceled, sets open, calls showModal(), moves focus. Returns false if a pd:open listener called preventDefault().
hide(reason?)(reason?: Reason) => booleanCancelable close. Fires pd:close; if not canceled, flips data-state="closed", makes the dialog inert, waits for exit animations, calls dialog.close(), restores focus, then fires pd:closed. Returns false if canceled.
toggle(force?, reason?)(force?: boolean, reason?: Reason) => booleanforce omitted flips current state; true/false forces show/hide.

reason defaults to 'api' for direct calls to show()/hide()/toggle().

Commands ​

commandfor targets the <dialog>'s id, not pd-drawer's.

CommandTargetEffect
show-modal (native)the <dialog>'s idIntercepted (preventDefault()) and routed through show('command') instead of the browser's instant, unanimated default.
close (native)the <dialog>'s idIntercepted and routed through hide('command').
--pd-toggle / --pd-open / --pd-closethe <dialog>'s idSame pipeline, explicit toggle/open/close.

Events ​

Dispatched from <pd-drawer> (bubbles: true, composed: true), not from the <dialog>.

EventCancelableWhendetail
pd:openyesbefore showModal() runs{ reason }
pd:closeyesbefore the close animation starts{ reason }
pd:openednoafter showModal() ran, data-state="open", and focus moved{ reason }
pd:closednoafter exit animations settled, dialog.close() ran, focus restored{ reason }

Reasons the drawer actually produces: 'command' (a show-modal/close/--pd-* invoker), 'api' (a direct show()/hide() call), 'escape' (native Escape), 'outside' (backdrop click), and 'attribute' (direct open attribute mutation — including the server-rendered-open case on connect, which skips events entirely).

Keyboard ​

KeyContextBehavior
Tab / Shift+Tabdialog openNative focus containment from showModal()'s top layer — cycles within the dialog, nothing outside is reachable.
Escapedialog openNative cancel fires; pd-drawer intercepts it (preventDefault()) and reroutes into hide('escape') so the exit animation plays instead of an instant close.
Enter / Spaceon a show-modal/close/--pd-* invokerNative button activation → command event → the pipeline above.

Accessibility ​

Managed by pd-drawer:

  • data-state="open"|"closed" mirrored on both <pd-drawer> and the <dialog>.
  • aria-expanded synced on every invoker of the dialog's id, live-queried so late-added buttons pick it up too. aria-controls is deliberately never set — commandfor already provides the programmatic association.
  • Focus moved into the dialog on open (a usable [autofocus] wins, else the first tabbable, then the dialog itself), explicitly restored to the exact command invoker or pre-API-open active element on close — but never yanks focus away if the author moved it elsewhere during the close animation.
  • Background inertness and top-layer stacking are native side effects of showModal(). Separately, the drawer applies component-owned inert to the dialog itself as soon as closing starts, so its rendered exit-animation controls cannot receive focus; it keeps the dialog modal until the animation settles, then closes it and restores focus. A rapid reopen invalidates that pending close and removes component-owned inertness before showModal()/focus; author-supplied inert is preserved.

Author must provide:

  • An accessible name on the <dialog> — aria-label="Menu" or aria-labelledby pointing at a heading inside. Dialogs have no implicit name.
  • A visible close control (command="close" button). Escape alone isn't discoverable for every user — a screen-magnifier or motor-impaired user scanning the dialog visually needs an on-screen way out, not just a keyboard shortcut.
  • Any landmark/heading structure inside the dialog — pd-drawer wraps behavior, never semantics.

Live demo ​

Your cart

  • Cleanser — 1
  • Moisturizer — 2
Checkout

Styling: Vanilla CSS ​

Complete, copy-pasteable. Ships alongside styles/base.css's UA reset (rule 1 below duplicates it for completeness — skip it if you already include that file).

css
/* 1. Reset UA dialog chrome so you style from zero. */
pd-drawer dialog {
  margin: 0;
  padding: 0;
  border: 0;
  max-width: none;
  max-height: none;
  background: transparent;
  color: inherit;
}

/* 2. Position + internal layout — grid, not nested flex. The header row
      (close button) and the scrollable content row are two grid tracks. */
pd-drawer dialog {
  position: fixed;
  inset-block: 0;
  inset-inline-end: 0;
  width: min(24rem, 100vw);
  height: 100%;
  grid-template-rows: auto 1fr;
  gap: 1rem;
  padding: 1.5rem;
  background: #fff;
  box-shadow: -12px 0 32px rgb(0 0 0 / 0.15);
}
/* Scope display to [open]. An unconditional author `display: grid` would
   override the UA's dialog:not([open]) { display: none } rule and leak the
   closed dialog visually into layout (managed inert still protects Tab/AT). */
pd-drawer dialog[open] {
  display: grid;
}

/* 3. Slide transform keyed on data-state, not [open]. `open` flips the
      instant showModal() runs; data-state="closed" is what stays true for
      the whole exit animation, right up until dialog.close() actually runs. */
pd-drawer dialog {
  transform: translateX(100%);
  transition: transform 240ms ease;
}
pd-drawer dialog[data-state='open'] {
  transform: translateX(0);
}
pd-drawer dialog[data-state='closed'] {
  transform: translateX(100%);
}

/* 4. Backdrop fade (exit only, see the @starting-style note below). */
pd-drawer dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
  opacity: 0;
  transition: opacity 240ms ease;
}
pd-drawer dialog[data-state='open']::backdrop {
  opacity: 1;
}

/* 5. Optional: entrance transition. Without @starting-style, a dialog and
      its ::backdrop simply appear at their target style the instant they're
      added to the top layer — there's no "before" frame to transition from.
      @starting-style supplies one (Chromium 117+, Firefox 129+, Safari
      17.5+); on older engines this block is ignored and only the exit
      (rule 3/4 above) animates, which is what the pipeline is built around
      regardless. */
@starting-style {
  pd-drawer dialog[data-state='open'] {
    transform: translateX(100%);
  }
  pd-drawer dialog[data-state='open']::backdrop {
    opacity: 0;
  }
}

/* 6. Respect reduced motion. */
@media (prefers-reduced-motion: reduce) {
  pd-drawer dialog,
  pd-drawer dialog::backdrop {
    transition: none;
  }
}

Styling: Tailwind ​

Tailwind ships a backdrop: variant that targets ::backdrop (distinct from the backdrop-blur/backdrop-opacity filter utilities, which style the element's own backdrop-filter). Pair it with the data-[state=…] arbitrary variant used throughout this library.

html
<button commandfor="menu-drawer" command="show-modal" class="rounded-md border px-3 py-2">
  ☰ Menu
</button>

<pd-drawer>
  <dialog
    id="menu-drawer"
    aria-label="Menu"
    class="
      m-0 max-h-none max-w-none border-0 bg-transparent p-0 text-inherit
      fixed inset-y-0 right-0 h-dvh w-full max-w-sm
      [&[open]]:grid grid-rows-[auto_1fr] gap-4 p-6
      bg-white shadow-2xl
      translate-x-full transition-transform duration-200 ease-out
      data-[state=open]:translate-x-0
      backdrop:bg-black/40 backdrop:opacity-0 backdrop:transition-opacity backdrop:duration-200
      data-[state=open]:backdrop:opacity-100
      motion-reduce:transition-none motion-reduce:backdrop:transition-none
    "
  >
    <button
      commandfor="menu-drawer"
      command="close"
      aria-label="Close menu"
      class="justify-self-end rounded-md border px-2 py-1"
    >
      ✕
    </button>
    <nav aria-label="Menu" class="grid gap-2 overflow-y-auto">…</nav>
  </dialog>
</pd-drawer>

justify-self-end on the close button works because the dialog is a grid container — no flex wrapper needed to align a single item.

See Drilldown → Mobile menu: drawer + drilldown composed for a full pattern combining pd-drawer with pd-drilldown, including resetting the drilldown to its root screen every time the drawer closes.