David Walsh
This article was created on April 15, 2024.
Creating a modal that overlays the rest of the webpage can now be done with native HTML and CSS. Any element with the popover attribute will act as the top layer, once a corresponding element (like a button) is clicked.
In the past, JavaScript code would have to be written in order to change the display value of a modal, in response to a particular event within the DOM. Now, we can create modals that listen to a user's click, with no JavaScript needed!
Of course, you can still use JavaScript to listen to events other than a click.
The content of your modal will be inside of an element with the popover attribute, as well as an id. A clickable element whose popovertaget matches this id will then trigger the modal to appear.
Use the [popover]
attribute selector to select your modal, and then style it to your liking.
The [popover]:-internal-popover-in-top-layer::backdrop
selector can be used to style the background color of the viewport, once the modal is visible.