Lesson 30 +10 XP

Modal

Modal

A modal is a popup dialog that appears on top of the page. It needs the Bootstrap JavaScript bundle.

Basic modal structure

<!-- Button to open the modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
  Open modal
</button>

<!-- The modal -->
<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        This is the body of the modal.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

The key pieces

  • The button uses data-bs-toggle="modal" and data-bs-target="#myModal".
  • .modal is the overlay container.
  • .modal-dialog sizes and centers the dialog.
  • .modal-content holds header, body, and footer.
  • .modal-header, .modal-body, .modal-footer split the content.
  • data-bs-dismiss="modal" closes the modal.

Sizing

  • .modal-sm small modal.
  • .modal-lg large modal.
  • .modal-xl extra large modal.
<div class="modal-dialog modal-lg">
  ...
</div>

Centering

Add .modal-dialog-centered to center the modal vertically:

<div class="modal-dialog modal-dialog-centered">
  ...
</div>

TL;DR

  • Modals need the JS bundle.
  • Open with data-bs-toggle="modal" + data-bs-target.
  • Close with data-bs-dismiss="modal".
  • .modal-dialog + .modal-content structure the popup.
  • .modal-sm, .modal-lg, .modal-xl size it.