How to use Bootstrap Modal

Modal is a responsive popup used to display extra content. That includes prompts, configurations, cookie consents, etc.

To use modal you need:

  • A trigger (for example a button)
  • Modal itself

After clicking the trigger (button) the modal is launched

          <!-- Button trigger modal -->
            class="btn btn-primary"
            Launch demo modal

          <!-- Modal -->
            class="modal fade"
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">
                    Modal title
                <div class="modal-body">...</div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">
                  <button type="button" class="btn btn-primary">
                    Save changes

Some details:

  • Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead.
  • Clicking on the modal “backdrop” will automatically close the modal.
  • Bootstrap only supports one modal window at a time. Nested modals aren’t supported as we believe them to be poor user experiences.
  • Modals use position: fixed, which can sometimes be a bit particular about its rendering. Whenever possible, place your modal HTML in a top-level position to avoid potential interference from other elements. You’ll likely run into issues when nesting a .modal within another fixed element.
  • Once again, due to position: fixed, there are some caveats with using modals on mobile devices.
  • Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

You can launch the modal via data attributes or via JavaScript

The modal plugin toggles your hidden content on demand, via data attributes or JavaScript. It also adds .modal-open to the <body> to override default scrolling behavior and generates a .modal-backdrop to provide a click area for dismissing shown modals when clicking outside the modal.

Via data attributes

Activate a modal without writing JavaScript. Set data-mdb-toggle="modal" on a controller element, like a button, along with a data-mdb-target="#foo" or href="#foo" to target a specific modal to toggle.

          <button type="button" data-mdb-toggle="modal" data-mdb-target="#myModal">
            Launch modal

Via JavaScript

Create a modal with a single line of JavaScript:

          const myModal = new mdb.Modal(document.getElementById('myModal'), options)