Sub topic 1
What the dialog element is
The <dialog> element is the HTML element for a window that sits on top of the page: a confirmation prompt, a small form, a message that needs attention. Before it existed, developers built these from <div> elements, z-index, focus-trapping scripts, and ARIA attributes. This chapter covers what the element is, what it does by default, and what the open attribute controls. Later chapters cover the opening methods, events, forms, styling, and accessibility in detail.
Prerequisites
This chapter assumes you can do the following:
- Write basic HTML structure, including forms, labels, and buttons.
- Read CSS selectors, including attribute selectors such as
[open]and pseudo-elements such as::backdrop. - Select elements with
document.getElementByIdorquerySelectorand attach event listeners in JavaScript.
You do not need to know ARIA. The relevant parts are explained as they come up.
The element in one sentence
A <dialog> is a block of content that is hidden until it is opened. When it is open, the browser displays it as a box above the surrounding content. Whether the rest of the page stays usable depends on how you open it, which the next chapter covers.
The smallest useful dialog looks like this:
<dialog open>
<p>Hello from a dialog.</p>
</dialog>The page shows a bordered box with the text inside. Remove the open attribute and nothing is displayed. The element is still in the DOM, but the browser hides it.
The open attribute is the state
A dialog has exactly two states, and one boolean attribute decides which one applies.
| State | Markup | What the user sees |
|---|---|---|
| Closed | `<dialog>` | Nothing. The element has `display: none`. |
| Open | `<dialog open>` | The dialog box and its content. |
The JavaScript property dialog.open reflects the attribute. It is true when the attribute is present and false when it is not.
<dialog id="status">
<p>Status panel</p>
</dialog>
<script>
const status = document.getElementById('status');
console.log(status.open); // false
status.setAttribute('open', '');
console.log(status.open); // true
console.log(status.hasAttribute('open')); // true
</script>You can open a dialog by setting the attribute, as above. In practice you should not. A dialog opened this way is always non-modal, and it skips the behavior the browser adds when you call the proper methods. Those methods are show() and showModal(), covered in the next two chapters. Use the open attribute in markup for a dialog that should be visible when the page loads. Let the methods change the state afterward.
What the browser gives you for free
The browser attaches several behaviors to <dialog> that a <div> would not have.
- Hidden by default. The browser's built-in stylesheet sets
display: noneon a dialog that has noopenattribute. You do not need a.hiddenclass. - Implicit role. A
<dialog>is exposed to assistive technology with the ARIA roledialog. You do not writerole="dialog"yourself. - Built-in methods.
show(),showModal(), andclose()exist on the element, so you do not write toggle logic. - Built-in events. The element fires
closeandcancelevents. - Default presentation. The built-in stylesheet gives the open dialog a border, padding, a background, and centering, so it looks like a box even with no CSS from you.
Several more behaviors apply only when the dialog is opened as a modal: the dialog moves to the top layer, the rest of the page becomes inert, the Escape key closes it, and a ::backdrop pseudo-element is drawn behind it. Those belong to later chapters. Here the point is that the element gives you the structure for all of that.
Default styles you will meet
You can see what the browser applies by opening the developer tools on any dialog and looking at the "user agent stylesheet" rules. The exact values differ slightly between browsers, but the important ones are close to these:
dialog:not([open]) {
display: none;
}
dialog {
position: absolute;
inset-inline: 0;
width: fit-content;
height: fit-content;
margin: auto;
border: solid;
padding: 1em;
background: Canvas;
color: CanvasText;
}Three of these matter right away:
width: fit-contentandmargin: auto. The dialog shrinks to fit its content and is centered horizontally. If you need a fixed or maximum width, set it yourself withwidthormax-width.background: Canvasandcolor: CanvasText. These are system colors. The dialog follows the page's light or dark color scheme (if you opt in withcolor-scheme) instead of defaulting to hard-coded white.position: absolute. An open non-modal dialog is positioned like any other absolutely positioned element. A modal dialog is placed differently, in the top layer relative to the viewport, which a later chapter explains.
You can override any of these with ordinary selectors. Start with a simple reset to see how little you need:
dialog {
border: 1px solid #888;
border-radius: 8px;
padding: 1.5rem;
max-width: 32rem;
}Where to put the element in your HTML
A <dialog> can sit almost anywhere in the body. Its closed state takes no space, so its position in the source does not change your layout. Two practical habits help:
- Keep dialogs near the end of
<body>, or next to the code that uses them. Either works. Putting a dialog inside a deeply nested container is allowed, but styles inherited from that container (font, color,text-align) will apply to the dialog's content when it is open. - Give each dialog an
id. Your script and your triggering buttons need a way to find it.
A dialog may contain any flow content: headings, paragraphs, images, forms, even other elements with their own scripts. The element does not restrict its children, but it works best with a clear structure of a heading, some content, and a set of actions:
<dialog id="confirm-delete" aria-labelledby="confirm-title">
<h2 id="confirm-title">Delete this file?</h2>
<p>This cannot be undone.</p>
<form method="dialog">
<button value="cancel">Cancel</button>
<button value="delete">Delete</button>
</form>
</dialog>The aria-labelledby attribute points to the heading so assistive technology can announce the dialog's name. The <form method="dialog"> is a special form that closes the dialog on submit. Both appear in full in later chapters. They are shown here so you recognize the shape of a typical dialog.
A complete first example
This page has a button and a dialog. The script uses showModal() to open the dialog and close() to close it. It is the minimum you need to see the element working end to end.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>First dialog</title>
</head>
<body>
<button id="open">Show message</button>
<dialog id="message" aria-labelledby="message-title">
<h2 id="message-title">Welcome</h2>
<p>This is a native dialog element.</p>
<button id="close">Close</button>
</dialog>
<script>
const message = document.getElementById('message');
document.getElementById('open').addEventListener('click', () => {
message.showModal();
});
document.getElementById('close').addEventListener('click', () => {
message.close();
});
</script>
</body>
</html>Run it and check three things. The dialog is invisible when the page loads. After you click the button, the box appears centered, with a dimmed page behind it. Pressing Escape closes it without any code from you. After the dialog closes, message.open is false again.
Common errors with the basic element
These mistakes come from not realizing that the open attribute and CSS display are linked.
Overriding display makes the dialog always visible
The built-in rule that hides a closed dialog is dialog:not([open]) { display: none; }. If you write your own rule that sets display on dialog, your rule can win and the closed dialog becomes visible.
/* Wrong: this shows the dialog even without the open attribute */
dialog {
display: flex;
flex-direction: column;
gap: 1rem;
}Scope the layout to the open state instead:
dialog[open] {
display: flex;
flex-direction: column;
gap: 1rem;
}This is the most common styling error with <dialog>. If a dialog is on screen when the page loads and you did not add open, check your display declarations first.
Using open on markup you meant to be modal
Writing <dialog open> in HTML always produces a non-modal dialog. The page behind it stays interactive, there is no backdrop, and Escape does nothing. If you want a modal, leave the attribute off and call showModal() from script.
Treating the attribute and the methods as interchangeable
Setting open and calling show() both give a non-modal open dialog, so they look the same on screen. They are not the same in behavior. The methods also handle focus, and they throw errors in certain invalid states. Prefer the methods in scripts.
Expecting the element to be centered vertically in every case
The browser's default styles center a dialog horizontally. For a modal dialog, they also center it vertically in the viewport. A non-modal dialog stays near its position in the document flow. If you want a non-modal dialog placed somewhere specific, position it yourself with CSS.
Browser support and fallbacks
<dialog> works in all current versions of Chrome, Edge, Firefox, and Safari. It has been available across all of them since early 2022, so you can use it without a library on any browser your project is likely to support. If you must support much older browsers, a polyfill exists, but it only approximates the native behavior. Check your project's support policy before adding one.
Summary of the element's job
- It represents content that appears above the page when opened.
- Its entire state is the boolean
openattribute, mirrored by thedialog.openproperty. - A closed dialog has
display: none. Do not override that with an unscopeddisplayrule. - It has the
dialogrole built in, so you only need to supply an accessible name. - Opening it through
showModal()orshow()is preferred to setting the attribute by hand.
The next chapter explains the difference between the two opening methods and when to choose each.
Exercise
A teammate adds dialog { display: grid; gap: 1rem; } to the stylesheet. After that, a dialog that has no open attribute appears on the page at load time. Why does this happen, and how do you fix it while keeping the grid layout for the open dialog?
Show answer
The browser hides a closed dialog with a built-in rule, dialog:not([open]) { display: none; }. The new dialog { display: grid; } rule overrides that display value, so the closed dialog is rendered. Scope the layout to the open state with dialog[open] { display: grid; gap: 1rem; }. The browser's rule then still applies when the attribute is absent.
Exercise
You write <dialog id="d" open> in the HTML and expect a modal. List two things you will observe that show it is non-modal, and say what you should change.
Show answer
The page behind the dialog stays interactive (you can click buttons and focus fields outside it), and there is no dimmed backdrop. Pressing Escape also does not close it. Remove the open attribute from the markup and call document.getElementById('d').showModal() from script to open it as a modal.
Exercise
What does dialog.open return after you call dialog.setAttribute('open', ''), and what does it return after you then call dialog.close()?
Show answer
It returns true after the attribute is set, because the property reflects the attribute. After close() it returns false, because close() removes the open attribute.