Dialogs and popovers
Definition and purpose
A modal dialog interrupts interaction with the rest of the page; an auto popover is a non-modal top-layer surface that can be dismissed. CSS styles these states, but HTML and the browser manage activation and dismissal.
Modal backdrop
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a::backdrop { background: rgba(0, 0, 0, 0.5); } </style> </head> <body> <button id="open" onclick="document.getElementById('a').showModal()">Open</button> <dialog id="a" aria-label="Confirm action"> <p>Confirm?</p> <form method="dialog"> <button>Close</button> </form> </dialog> </body></html>Click Open; the backdrop appears and the Close button submits the dialog form without navigation.
Syntax and mental model
A dialog opened with showModal() enters the top layer and makes the rest of the document inert. The small script in the first example calls that native method. ::backdrop styles its backdrop. The second uses HTML popovertarget and :popover-open; a popover is not automatically a modal dialog.
Open state
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a:popover-open { border: 3px solid navy; } </style> </head> <body> <button id="open" popovertarget="a">Help</button> <div id="a" popover>Helpful information</div> </body></html>The Help button toggles a native popover.
Common mistakes
Do not use z-index alone to simulate a modal. Provide an accessible name in real dialogs, a close control and a sensible focus target.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Selects, checkboxes, range and meters. Next lesson: Scrollbars, interaction and resize.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dialogs and popovers — knowledge check
Five questions on dialogs and popovers.
Which method opens a modal dialog?
Which pseudo-element styles the backdrop?
Which selector matches an open popover?
Is an auto popover modal by default?
What does popovertarget reference?