Create modal using the <dialog> element.
Requires Svelte v5 and runes mode.
$state(boolean)<body> scrolling while the modal is open<dialog> element with focus trap and Esc supportoncancel and onclose event handlers are supportedTo upgrade from previous versions, see the migration guide.
pnpm add svelte-html-modal -D
npm i svelte-html-modal -D
<script>
import { Modal } from 'svelte-html-modal';
// Client-side JavaScript is required to display the modal.
// Reference https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal
let isOpen = $state(false);
const open = () => (isOpen = true);
const close = () => (isOpen = false);
</script>
<button type="button" onclick={open}>Open Modal</button>
<!-- The wrapper <div> is used for styling. -->
<!-- Reference the <style> element below. -->
<div class="modal-wrapper">
<Modal bind:isOpen>
<strong>Close the Modal</strong>
<ul>
<li>Click on the backdrop</li>
<li>Press the <kbd>Esc</kbd> key</li>
<li><button type="button" onclick={close}>JavaScript Button</button></li>
<li>
<!-- Reference https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method -->
<form method="dialog">
<button>Submit Button</button>
</form>
</li>
</ul>
</Modal>
</div>
<!-- Vanilla CSS -->
<style lang="postcss">
/* Style <dialog> within the .modal-wrapper element. */
/* Reference https://svelte.dev/docs/svelte/scoped-styles */
.modal-wrapper :global {
> dialog {
width: 20rem;
padding: 1rem;
border-radius: 0.375rem;
&::backdrop {
backdrop-filter: blur(8px) brightness(0.5);
}
}
}
</style>
Tailwind CSS v4 can be used as well:
<!-- using variables -->
<style lang="postcss">
.modal-wrapper :global {
> dialog {
margin: auto;
width: calc(var(--spacing) * 80);
border-radius: var(--radius-md);
padding: calc(var(--spacing) * 4);
&::backdrop {
backdrop-filter: blur(8px) brightness(0.5);
}
}
}
</style>
<!-- using @apply -->
<style lang="postcss">
/* https://tailwindcss.com/docs/functions-and-directives#reference-directive */
@reference "../../app.css";
.modal-wrapper :global {
> dialog {
@apply m-auto w-80 rounded-md p-4 backdrop:backdrop-blur backdrop:backdrop-brightness-50;
}
}
</style>
[!NOTE]
For fullscreen modal, override max-size values:
dialog {
/* Override user-agent dialog:modal max-sizes. */
max-height: 100%; /* calc((100% - 6px) - 2em); */
max-width: 100%; /* calc((100% - 6px) - 2em); */
}
{
"closeOnBackdropClick": false,
"closeOnEscapeKey": true
}
<Modal
bind:isOpen
id="string"
closeOnBackdropClick={false}
closeOnEscapeKey={true}
oncancel={(e) => {}}
onclose={(e) => {}}
>
<!-- Children -->
</Modal>
[!IMPORTANT]
ThecloseOnEscapeKeyprop has a known issue in Chrome 126~133. The modal can be closed by pressing theEsckey twice. This will be resolved in a future update when theclosedbyattribute is implemented. Learn more