Skip to main content

Archive

Show more

Bootstrap Modals

Bootstrap Modals

Bootstrap modals are flexible dialog boxes that can contain various content types, such as text, forms, images, or even other Bootstrap components. They are commonly used for displaying alerts, prompts, or additional information without navigating away from the current page. Here's how to use Bootstrap modals:


1. Basic Modal

To create a basic modal, use the modal class along with the modal-dialog and modal-content classes. Inside the modal content, include a header, body, and footer as needed:

<div class="modal" tabindex="-1">
  <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" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Use the data-bs-toggle="modal" attribute to trigger the modal:

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

2. Modal Sizes

Bootstrap provides options for sizing modals, including small, large, and extra-large. Use the modal-dialog-centered class to center the modal vertically:

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

3. Modal Scrollable

If the modal content exceeds the available height, you can make the modal body scrollable by adding the modal-dialog-scrollable class:

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

4. Using JavaScript for Modals

To control the modal via JavaScript, you can use Bootstrap's modal methods. For example, to show a modal programmatically:

var myModal = new bootstrap.Modal(document.getElementById('exampleModal'))
myModal.show()

Similarly, you can hide a modal:

myModal.hide()

Conclusion

Bootstrap modals provide a convenient way to display content in a modal dialog, allowing users to focus on specific tasks or information without navigating away from the current page. By following these guidelines, you can effectively use modals to enhance the user experience and improve the usability of your web applications.

Comments