Bootstrap ยท Chapter 25 of 43

Bootstrap Modal

A modal is a dialog box that appears on top of the page content, often used for confirmations, forms, or extra details, without navigating away from the current page.

A modal is triggered by a button with data-bs-toggle="modal" and data-bs-target pointing at the modal's id. The modal itself contains a header, body, and footer section.

Syntax
<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">...</div>
  </div>
</div>

Modal structure

A modal has an outer .modal div (hidden by default), a .modal-dialog for sizing/positioning, and a .modal-content box containing .modal-header, .modal-body, and .modal-footer.

Closing a modal

A close button with data-bs-dismiss="modal" closes the modal. Clicking outside the modal or pressing Escape also closes it by default.

Example 1 (html)
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Open Modal
</button>

<div class="modal" id="exampleModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Confirm Action</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">Are you sure you want to continue?</div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary">Confirm</button>
      </div>
    </div>
  </div>
</div>
Output
Clicking 'Open Modal' displays a centered dialog with a title, message, and Cancel/Confirm buttons

data-bs-toggle and data-bs-target open the modal by id, and data-bs-dismiss closes it.

Example 2 (html)
<div class="modal-dialog modal-lg">...</div>
Output
A wider, large-sized modal dialog box

modal-lg increases the modal's width; modal-sm makes it smaller instead.

Key points

  • Modals are triggered with data-bs-toggle="modal" and data-bs-target.
  • The .modal-dialog controls the modal's size and position.
  • .modal-header, .modal-body, .modal-footer structure the content.
  • data-bs-dismiss="modal" closes the modal.
๐Ÿ’ก Note: Only one modal should be open at a time; nesting modals inside modals is not recommended.

๐Ÿ“ Quick Quiz

1. Which attribute opens a modal when clicked?

2. Which class makes a modal wider?

3. Which attribute closes a modal?