Skip to main content

Building a Bootstrap Modal with the dialog HTML element

Posted on
Contents

Continuing my series of posts on building Bootstrap components using just CSS and native HTML elements, this post demonstrates how to create a Bootstrap modal dialog using the <dialog> HTML element.

The <dialog> element has been supported by all major browsers for a while now and can be used with Invoker Commands and is a great way to create a modal dialog without the need of JavaScript.

You can create a Bootstrap modal using the <dialog> element with just a tiny bit of custom CSS.

html
<button class="btn bg-primary btn-primary" type="button" id="btnDialog" commandfor="dialog"
  command="show-modal" closedby="any">
  Open modal
</button>

<dialog id="dialog" class="position-relative border-1" closedby="any">
  <div class="modal d-flex position-static">
  <div class="modal-dialog w-100 m-0">
    <div class="modal-content bg-body">
      <div class="modal-header">
        <h1 class="modal-title fs-5 mt-0">Modal title</h1>
        <form method="dialog" class="ms-auto me-1">
          <button type="submit" class="btn-close">
            <span class="visually-hidden">Close</span>
          </button>
        </form>
      </div>
      <div class="modal-body py-2">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</dialog>

<style>
dialog {
  background-clip: padding-box;
  background-color: var(--bs-body-bg);
  border-radius: var(--bs-border-radius-lg);
  border: 1px solid var(--bs-border-color);
  box-shadow: var(--bs-box-shadow-sm);
  color: var(--bs-body-color);
  max-width: 100%;
  min-width: 420px;
  overflow-x: hidden;
  overflow-y: auto;
  padding: var(--bs-modal-padding-y) var(--bs-modal-padding-x);
  z-index: var(--bs-modal-zindex);

  &::backdrop {
    background-color: rgba(0,0,0,.75);
    animation: .3s fade-in;
  }
}
</style>

Demo

You can also view an external demo.

Considerations

  • Invoker commands are now supported in all modern browsers. In order to support older browsers, you can add the invokers polyfill.
  • The above example allows the user to dismiss the modal by clicking outside of it or pressing the Escape key. If you want to prevent this behavior, you can remove the closedby="any" attribute from the <dialog> element.
  • The dialog element fades in when opened using the ::backdrop pseudo-element and Bootstrap’s own fade-in animation, but when dismissing the dialog it doesn’t fade out.
  • Bootstrap 6 will likely rename the modal component to dialog and use the <dialog> element and there’s an open PR on GitHub.

You might also like