Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 58 ยท Components

Modals

Build Bootstrap 5.3 modal dialogs: markup, sizes, scrollable and centered modals, fullscreen, static backdrops, events, and passing data from the trigger button.

A modal is a dialog that appears on top of the page and asks for attention: confirm a deletion, show a sign-in form, display a larger photo. The page behind it is dimmed and, while the modal is open, the visitor cannot interact with anything else. Bootstrap's modal plugin handles the dimming, the animation, the keyboard (Escape closes it), and moving keyboard focus into the dialog and back.

Like Accordion and Collapse, a modal needs the Bootstrap JavaScript bundle and is wired together with data-bs-* attributes. This lesson covers the standard markup, the option classes (size, scrolling, centering, fullscreen), the static backdrop, the events a modal fires, and how to pass data from a button into the dialog.

The basic structure

A modal is a stack of nested elements. Each layer has one job:

flowchart TD
  M[".modal.fade<br/>full-screen overlay and the id"] --> D[".modal-dialog<br/>sets size and position"]
  D --> C[".modal-content<br/>the white box"]
  C --> H[".modal-header<br/>title and close button"]
  C --> B[".modal-body<br/>your content"]
  C --> F[".modal-footer<br/>action buttons"]

The four layers of a modal: overlay, dialog, content, and the three optional sections.

A button opens it with data-bs-toggle="modal" and data-bs-target="#id". Inside, a button with data-bs-dismiss="modal" closes it. The close "X" is the btn-close class, and it needs an aria-label because it has no text.

A basic modal

Some details in that markup matter:

  • tabindex="-1" on the overlay lets the plugin move focus to it without putting it in the normal tab order.
  • aria-labelledby points at the title's id, so a screen reader announces "Delete this project? dialog" when it opens.
  • fade makes the dialog slide in and out. Remove it for an instant appearance.
  • The modal markup can live anywhere in the body, but placing it at the top level (not inside another positioned element) avoids stacking problems. Many projects put all modals just before the closing </body>.
  • Only one modal should be open at a time. Bootstrap does not support stacking a second modal on top of the first.

Sizes, centering and scrolling

Everything about the dialog's shape is controlled by classes on .modal-dialog:

Class Effect
modal-sm 300 px wide
(none) 500 px wide, the default
modal-lg 800 px wide
modal-xl 1140 px wide
modal-dialog-centered vertically centered instead of near the top
modal-dialog-scrollable the body scrolls, header and footer stay put
modal-fullscreen covers the whole viewport
modal-fullscreen-md-down fullscreen below the md breakpoint (also sm-down, lg-down, xl-down, xxl-down)

Without modal-dialog-scrollable, a very tall modal makes the whole overlay scroll with the page's scroll bar. For long terms-and-conditions text, scrollable is nicer because the buttons remain visible. Sizes below their stated width shrink on narrow screens automatically, since all of this is responsive.

The -down fullscreen classes are a good mobile pattern: a comfortable dialog on a laptop, a full-screen sheet on a phone.

Large, centered and scrollable

The second modal has no header or footer. Every section inside .modal-content is optional, so a simple notice can be just a body.

Content inside a modal: grids, tooltips and a second modal

A modal body is an ordinary container, so layouts work inside it, with a few rules.

  • Grid. Put a container-fluid inside modal-body and use row and col-* as usual. The col-md-* breakpoints respond to the viewport width, not the dialog width, so inside a narrow modal-sm dialog prefer plain col-* classes.
  • Tooltips and popovers. Initialize them with the container option set to the modal element (new bootstrap.Tooltip(el, { container: '#myModal' })). Without it, the tooltip is appended to body, which can render under the modal or lose position when the modal scrolls.
  • A second modal. Bootstrap does not support stacking two modals. To go from one to another, hide the first and show the second when it has finished hiding, as the example does. Alternatively, switch the body content inside one modal.
  • Focus. Call focus() in shown.bs.modal for the first field; the modal itself moves focus to the dialog, which is not always the right place for a form.
Grid, tooltip and a modal hand-off

Press Next step: the first modal fades out, and only after hidden.bs.modal does the second one start. Opening both at once leaves two backdrops and broken focus handling.

Static backdrop

By default, clicking the dimmed backdrop or pressing Escape closes the modal. For a form with unsaved work, that is risky. Two attributes change it:

  • data-bs-backdrop="static" keeps the backdrop but ignores clicks on it. The modal gives a small "bounce" to show the click was noticed.
  • data-bs-keyboard="false" disables Escape.

With both set, the only ways out are your own buttons, which is what you want for a required choice. Use this sparingly: forcing people to answer is a poor experience for ordinary announcements. And if you remove the header close button too, make sure the footer offers a clear exit.

Events

The plugin fires events on the modal element, so your page can react to what happens. There are two pairs: the "-ing" event fires when the action starts, the "-ed" one when the animation ends.

Event When it fires
show.bs.modal right after the show was requested, before the modal is visible
shown.bs.modal once the modal is visible and the transition finished
hide.bs.modal when hiding starts
hidden.bs.modal after the modal is hidden and the transition finished
hidePrevented.bs.modal when closing was blocked (static backdrop)

shown.bs.modal is the right moment to focus a field, for example input.focus(), because the element is only focusable once visible. hidden.bs.modal is the place to reset a form. The next lesson on events covers calling preventDefault() on the "-ing" events.

Passing data into a modal

Often one modal serves many buttons: a "Delete" button for each row of a table, all opening the same confirmation. The trigger button can carry data in its own data-bs-* attribute, and the modal reads it from event.relatedTarget, which is the element that caused the opening.

One modal, three buttons

Look at what the script does. On show.bs.modal it reads the button's data-bs-file value and writes it into the modal text with textContent. Using textContent (not innerHTML) is important: file names come from users, and inserting them as HTML would open the door to script injection.

relatedTarget is only set for data-attribute openings. If you open a modal from your own JavaScript code, there is no clicked button, so event.relatedTarget is undefined unless you pass one in.

Accessibility and mistakes to avoid

Bootstrap returns focus to the opening button when the modal closes, and traps keyboard focus inside while it is open. Your part is to give the dialog an accessible name (aria-labelledby or aria-label) and a visible way to close it.

  • Do not nest modals. Place each modal at the top level of the page, not inside another modal.
  • Do not forget aria-hidden="true" on the closed markup; the plugin manages it afterward.
  • Avoid sticky or transformed parents. A modal inside an element with transform or overflow: hidden can be clipped or mispositioned.
  • Do not use a modal when a simple message will do. Interrupting someone is expensive; prefer an alert or toast for non-critical information.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which attributes on a button open the modal with id="login"?

    data-bs-toggle="modal" selects the plugin and data-bs-target is a selector for the modal element.
  2. 2. Which class on .modal-dialog keeps the header and footer in place while only the body scrolls?

    modal-dialog-scrollable makes the body scroll inside the dialog. Centered only changes vertical position.
  3. 3. How do you stop a modal from closing when the visitor clicks outside it or presses Escape?

    A static backdrop ignores clicks outside, and data-bs-keyboard="false" disables the Escape key.
  4. 4. In a show.bs.modal handler, how do you find the button that opened the modal?

    event.relatedTarget is the triggering element for modals opened through data attributes. event.target is the modal itself.
  5. 5. When is the best moment to focus a text field inside a modal?

    At show.bs.modal the dialog is not visible yet, so the field cannot take focus. shown.bs.modal fires after the transition.

Summary

  • A modal has an overlay (.modal), a .modal-dialog, .modal-content and optional header, body and footer.
  • Open with data-bs-toggle="modal" and data-bs-target; close with data-bs-dismiss="modal".
  • Size and behavior come from classes on .modal-dialog: modal-sm/lg/xl, modal-dialog-centered, modal-dialog-scrollable, modal-fullscreen*.
  • data-bs-backdrop="static" and data-bs-keyboard="false" make a modal impossible to dismiss by accident.
  • Events show, shown, hide, hidden and hidePrevented let you react; event.relatedTarget gives you the trigger and its data.
  • Name the dialog with aria-labelledby, keep one modal open at a time, and write user data with textContent.

Next lesson: Dropdowns, Tooltips and Popovers.