Is there a way to make a modal close with just html and css
The modal will open up and can be closed via a exit button,but also by clicking outside of the modal window.;is there any way to do this with just pure html and css,no javascript?
15 Replies
Yes. Use the
dialog
element (to get the "click outside to close" functionality) and add the popover
attribute to get the open/close functionality.MDN Web Docs
Using the Popover API - Web APIs | MDN
The Popover API provides developers with a standard, consistent, flexible mechanism for displaying popover content on top of other page content. Popover content can be controlled either declaratively using HTML attributes, or via JavaScript. This article provides a detailed guide to using all of its features.
You add the
popover-target="<id of popover element>"
to a button and it'll toggle the popover. Or add the popovertargetaction="hide"
to be only a close button.actually
you can do much worse, but works much better
add an hidden form inside the dialog
give it an id - ideally
<dialog id>-close
then, add a button of type submit, with the form attribute set to that form
oh, and the form needs to have method="dialog"
when you submit a form with that method, inside a dialog, it closes the dialog
the click outside can work if you go 3 levels deeper into the jank, which i do not recommendIs it better or worse? 🤔
much much worse than your method, but more compatible
by the way, with my method the opening needs javascript
but you will need to use javascript anyways, until the popover support is better
Yep. The
popover
attribute is new: 2024yup
in short, the answer is "kinda almost"
a little tangent: why close the dialog when clicking outside the area?
thats the fastest way to get angry emails from users who lost the form data
(that and throwing away everybody's settings for your app)
Its for a blog where the layout will have a modal come out and take up the entire right side to show more contextual info
ah that makes sense to have the dialog close when you click outside
Popover allows light dismiss (clicking outside) and doesn’t require js ; as 13 mentioned you can map open and close buttons via popovertargetaction.
But depends how good you need support to be; as of the time of writing , popover / popovertarget / popovertargetaction attrs are Baseline Support
caniuse
Thats good enough i think,im using it for tauri and theyre using native webview.the primary platforms im aiming for are windows and linux
These tables are for browser support fyi (chrome safari opera Firefox etc) and windows / Linux are operating systems/oS
So long as they are targeting the right webkit for macOS. Then what ever Edge supports.