WebTech1223411 logo WebTech1223411Web tech, read closely
Accessibility

How to Build an Accessible Modal Dialog That Works

A modal opens, a keyboard user presses Tab, and focus quietly slips behind the overlay into a page they can no longer see. A screen reader user hears nothing at all when it opens, or keeps reading the article underneath.

A monitor showing a web page dimmed behind a centred confirmation dialog with a highlighted Cancel button, a keyboard in front of it

A modal opens, a keyboard user presses Tab, and focus quietly slips behind the overlay into a page they can no longer see. A screen reader user hears nothing at all when it opens, or keeps reading the article underneath. Building an accessible modal dialog used to mean 150 lines of focus trapping JavaScript and a stack of ARIA attributes. Today the native dialog element does most of that work, as long as you open it the right way and handle a few details it leaves to you.

I have shipped and audited modals on everything from checkout flows to cookie banners. Here is the approach that holds up in testing with keyboards, NVDA, VoiceOver and real users.

What an accessible modal dialog has to do

Before writing code, it helps to list the behaviours users rely on. The WAI-ARIA Authoring Practices pattern for modal dialogs boils down to these:

  1. Move focus into the dialog when it opens, usually to the first interactive control or to the dialog heading.
  2. Keep focus inside while it is open. Tab and Shift Tab cycle through the dialog's controls only.
  3. Make the rest of the page inert, so screen readers and pointer clicks cannot reach it.
  4. Close on Escape and through a clearly labelled close button.
  5. Return focus to the element that opened it when it closes.
  6. Announce a name, so a screen reader says something like "Delete project, dialog" rather than just "dialog."

Miss any one of these and some group of users gets stuck.

Use the native dialog element with showModal

The HTML dialog element has been supported in all major browsers since 2022. The important part is how you open it. Calling the showModal() method gives you modal behaviour; calling show() or setting the open attribute does not.

With showModal(), the browser handles a lot for you:

  • The dialog is placed in the top layer, above every z-index on the page.
  • Everything outside the dialog becomes inert, which covers both screen readers and mouse clicks.
  • Pressing Escape closes the dialog and fires a cancel event, then a close event.
  • Focus moves into the dialog automatically.
  • A ::backdrop pseudo-element lets you style the dimmed overlay with plain CSS.

Give the dialog an aria-labelledby attribute that points to the id of its visible heading, so it has an accessible name. If the dialog holds a short message rather than a form, add aria-describedby pointing at that message so screen readers read it on open.

The details the browser leaves to you

Choosing initial focus

By default, the browser focuses the first focusable element inside the dialog. That is often the close button in the top corner, which is a poor starting point for a form. Put the autofocus attribute on the control that should receive focus. For destructive confirmations such as "Delete this project," focus the safer Cancel button, not Delete.

For dialogs with long content, such as terms or a multi-step form, focus the heading instead. Give it tabindex="-1" so it can receive focus programmatically without joining the tab order. Screen reader users then start at the top rather than halfway down.

Returning focus on close

Browsers are inconsistent about restoring focus when a dialog closes. Store a reference to the triggering button before calling showModal(), then listen for the close event and call focus() on that stored element. Without this, keyboard users get dropped at the top of the document and have to tab all the way back. Our article on keyboard navigation testing shows how quickly this sort of failure shows up when you put the mouse away.

A visible close button

Escape is not discoverable for everyone, and many touch screen users have no Escape key. Always include a real button element to close the dialog. If it uses only an icon, give it an accessible name such as aria-label="Close". A form inside the dialog with method="dialog" will close it on submit without any JavaScript.

Focus styles

Dialogs often get custom styling, and custom styling often removes outlines by accident. Check that every control inside the dialog shows a clear focus indicator against the dialog background. We wrote about why focus outlines keep disappearing and how to restore them without making designers unhappy.

Do not close the dialog on every backdrop click

Many component libraries close a modal whenever the user clicks the dimmed backdrop, and lots of tutorials recommend it as a convenience. I think it should be the exception rather than the default.

For a simple image preview or an informational popup, closing on backdrop click is fine. For anything with input, it is a trap. A user selecting text in a long form field can release the mouse a few pixels outside the dialog, and the browser registers a click on the backdrop. The dialog vanishes along with everything they typed. Users with tremors or who rely on head pointers and other alternative pointing devices hit this far more often.

If you do support backdrop closing, only do it for dialogs with no form fields, and check that the pointer went down and came up on the backdrop itself, not just that a click event landed there. For forms, keep the close button and Escape as the only ways out, and ask for confirmation if there are unsaved changes.

Animation, scrolling and testing

An opening animation of 150 to 200 milliseconds feels smooth. Anything longer delays focus and can confuse screen reader timing. Respect the user's motion settings by disabling scale and slide effects under the reduced motion media query; our guide to supporting prefers reduced motion has the pattern.

Long dialogs should scroll internally with a max-height of around 85vh, while the page behind stays still. Setting overflow: hidden on the body while the dialog is open stops the background from scrolling on most devices.

Then test it by hand. A five minute routine catches nearly every problem:

  1. Open the dialog with Enter on its trigger, using only the keyboard.
  2. Press Tab repeatedly and confirm focus never leaves the dialog.
  3. Press Escape and confirm focus lands back on the trigger.
  4. Repeat with NVDA or VoiceOver running and listen for the dialog's name on open.
  5. Zoom the page to 200 percent and confirm the dialog content still fits or scrolls.

Frequently asked questions

Is the HTML dialog element accessible?

Yes, when opened with showModal(). It provides focus management, an inert background, Escape to close and the correct dialog role. You still need to give it an accessible name, set sensible initial focus and return focus to the trigger when it closes.

Do I still need aria-modal on a dialog element?

Not when you use showModal(), because the browser already treats it as modal and makes the background inert. Adding aria-modal="true" does no harm, but it matters mainly for custom modals built from div elements.

Should a modal trap keyboard focus?

Yes. While a modal is open, Tab and Shift Tab should cycle only through its controls, because the page behind it is not usable. The native dialog element handles this for you through the inert background when opened as a modal.

LV
Lorenzo Vidal

Lorenzo started as a visual designer and moved into CSS after watching too many of his layouts fall apart on phones. He writes about front-end craft, interfaces and accessibility, and still tests everything with the keyboard first.

More posts by Lorenzo

More in Accessibility

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto