Sub topic 3
Styling the dialog and its backdrop
Assume basic HTML, CSS selectors, and JavaScript event listeners. The <dialog> element is the modal surface. Its ::backdrop pseudo-element represents the page-covering layer behind it.
Styling the dialog and its backdrop
Remove the browser’s default border and use an inner wrapper for padding. This makes backdrop-click detection predictable.
dialog {
border: 0;
border-radius: 0.5rem;
padding: 0;
max-width: min(32rem, 90vw);
}
dialog > .content {
padding: 1.5rem;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
}
body:has(dialog[open]) {
overflow: hidden;
}A modal opened with showModal() enters the top layer. The backdrop belongs to that layer, so it does not need a high z-index.
Closing when the user clicks the backdrop
A click on the dialog element itself indicates that the user clicked outside the inner content. Close the dialog with an optional result value.
const dialog = document.querySelector("dialog");
dialog.addEventListener("click", (event) => {
if (event.target === dialog) {
dialog.close("dismissed");
}
});Making dialogs accessible
Give every dialog an accessible name. A visible heading connected with aria-labelledby is usually the clearest option.
<dialog aria-labelledby="settings-title">
<div class="content">
<h2 id="settings-title">Settings</h2>
<button type="button">Close</button>
</div>
</dialog>A modal makes the rest of the page inert, so keyboard users cannot interact with background controls. Set initial focus deliberately with autofocus when appropriate. After closing, focus normally returns to the element that opened the dialog.
Animating a dialog with CSS
display and overlay need discrete transitions so the dialog remains visible during the fade.
dialog {
opacity: 0;
transition:
opacity 200ms ease,
display 200ms allow-discrete,
overlay 200ms allow-discrete;
}
dialog[open] {
opacity: 1;
}
@starting-style {
dialog[open] {
opacity: 0;
}
}
dialog::backdrop {
background: rgb(0 0 0 / 0);
transition: background 200ms ease;
}
dialog[open]::backdrop {
background: rgb(0 0 0 / 0.5);
}Pitfalls to avoid
- Do not call
showModal()when the dialog is already open. Close it first. - Use
show()for non-modal content. It leaves the page interactive and has no modal backdrop. - Do not remove the visible heading just to simplify markup. Connect it with
aria-labelledby. - Test reduced-motion preferences and browsers that lack discrete-transition support.
Exercise
Why does the backdrop-click handler compare event.target with the dialog element?
Show answer
A click on the dialog element itself identifies the backdrop area, while clicks inside the content wrapper target a child element.