svelte-micromodal

svelte-micromodal is a Svelte wrapper around Micromodal to create light, accessible modal dialogs.

Here's a basic example:

Usage

Here's the Svelte markup for the example modal above:

<script>
  import { Modal, showModal, closeModal } fom "svelte-micromodal";
</script>

<!-- 1 -->
<button on:click={() => showModal("modal-basic")}>
  Open the modal
</button>

<!-- 2 -->
<Modal title="A basic modal" id="modal-basic" closeLabel="Close modal">
  <p>This is the modal body.</p>
  <p>It can contain anything—the first interactive element will receive focus when the modal is opened.</p>
  <footer>
    <button>Stay here</button>
    <button on:click={() => closeModal("modal-basic")}>Close modal</button>
  </footer>
</Modal>
  1. To open the modal, call the showModal() method with the modal id
  2. Pass the id as a prop to the Modal component, along with other required props
  3. To close the modal on button click, call the closeModal() method with the modal id. The built-in close button takes care of this for you.

Configuration

Any of Micromodal's configuration options can be passed as a second argument of the showModal() method.

For example, to create a modal that prevents page scroll while it's open, and that has a custom onShow callback, you could do this:

<button on:click={() => showModal("modal-config", {
  disableScroll: true,
  onShow: () => console.log("Called onShow()"),
})}>
  Open the modal
</button>

<Modal id="modal-config" />

Which results in:

Styling

The modal comes with little default UI, although enough to make it usable out of the box.

It will also inherit some of your global styles, in order to make it consistent with the rest of your UI (e.g. the modal's title will inherit any global h2 rules; the modal's copy will inherit the currentColor).

If you need to customize the default styles, custom styles can be passed as props to all modal DOM elements, either via inline styles or with classes. You can also pass a custom closeIcon SVG to override the built-in icon.

For example, here's how you could add dark mode support to a modal:

<Modal
  title="A modal with dark mode"
  id="modal-styles"
  closeLabel="Close modal"
  containerStyles="background-color:var(--color-bg);color:var(--color-text);"
>
  <p>This modal supports dark mode!</p>
  <!-- ... -->
</Modal>

<style>
  :global(html) {
    --color-bg: white;
    --color-text: black;
  }
  @media (prefers-color-scheme: dark) {
    :global(html) {
      --color-bg: black;
      --color-text: white;
    }
  }
</style>

Contact

Report issues, suggest improvements or simply ask questions on the GitHub repository. Thank you in advance!