CSS-only Modal Dialog
Can we code a modal dialog with CSS only? No.
State of the spec
As of this writing:
Now there's an HTML dialog element that has baseline browser support.
People still want a way to open it via HTML.
People in that thread were dismissive and indicate that commandfor and command attributes will allow such interactivity.
But so far the command attributes are still experimental.
So, if we want a HTML/CSS-only solution, what we currently have:
No, we can't open a dialog with HTML.
Yes, we can close a dialog with HTML.
So there's still gonna be a sprinkling of JavaScript.
An HTML-only example
With this, you can open a dialog that is modal, accessible, can exit on pressing escape or by clicking the close button.
<dialog id="popover">
Jake in the dialog
<form method="dialog">
<button autofocus>X</button>
</form>
</dialog>
<button type="button" onclick="document.getElementById('popover').showModal()">Toggle modal</button>
Notice that to open the modal, we call Dialog.showModal()
in JavaScript. :/
And style it with some CSS:
dialog {
border: none;
border-radius: 1rem;
padding: 1rem 2rem;
}
::backdrop {
background-image: linear-gradient(
45deg,
magenta,
rebeccapurple,
dodgerblue,
green
);
opacity: 0.75;
}
Notice that you can target the dialog element and the backdrop overlay when the dialog is opened.
Here's a working example.
That's really what's available right now. If you found a less-JavaScript solution, I'd love to hear about it.