<dialog> creates a dialog. showModal() opens it in the top layer and makes the rest of its document inert while it is open. show() opens a nonmodal dialog, and an open attribute alone does not make it modal.
A working modal dialog
HTML and CSS
HTML
<button id="open" type="button">Open reading tip</button>
<dialog aria-labelledby="dialog-title">
<h2 id="dialog-title">Reading tip</h2>
<p>Try changing one CSS value at a time.</p>
<button id="close" type="button" autofocus>Close tip</button>
</dialog>
<script>
const dialog = document.querySelector("dialog");
document.querySelector("#open").addEventListener("click", () => dialog.showModal());
document.querySelector("#close").addEventListener("click", () => dialog.close());
</script>
CSS
/* Optional presentation */
button {
font: inherit;
padding: 0.5rem 1rem;
}
dialog {
max-width: min(28rem, 80vw);
border: 1px solid #64748b;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.3);
}
Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.
Activate the opener with Enter or Space. Focus goes to the close button. While the modal is open, Tab stays within the dialog. Press Escape or activate Close to dismiss it; check that focus returns to the opener. The modal affects only this isolated preview document.
Naming and focus
aria-labelledby connects the dialog to its visible heading. Choose an initial focus target that fits the task; for a destructive action, a safe cancel action is often preferable. Avoid automatically focusing a destructive control.
Do not add tabindex to the dialog element. Put controls or a suitable focus target inside it. An accessible name identifies the dialog, while its visible content explains the task.
A practical use
A short confirmation or preference task can belong in a dialog when interrupting the current page is justified. Keep a visible dismissal control. close() can provide a return value for application logic. A form with method="dialog" normally closes a containing dialog without a network submission, but this site’s preview deliberately disallows form submissions, so the working example uses explicit close behavior.
Common mistakes
Toggling CSS display does not reproduce native modal behavior. A high z-index does not supply inertness, focus handling, or top-layer membership. Basic dialog support and newer features such as closedby have separate compatibility entries; verify the exact feature you use.
Sources and browser support
MDN: dialog describes the syntax and links to the specification and compatibility data. Check individual values in that table when supporting older browsers.