What is a Modal?
A modal is a popup window that appears on top of the page. The rest of the page is dimmed until the user closes it. Modals are used for confirmations, login forms and image previews.
Basic Modal
html
<!-- Button to open -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#demoModal">
Open Modal
</button>
<!-- Modal -->
<div class="modal fade" id="demoModal" tabindex="-1" aria-labelledby="demoModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="demoModalLabel">Modal Title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
This is the modal content.
</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>
How It Works
- The button has
data-bs-toggle="modal" and data-bs-target="#demoModal".
- The modal has the matching
id="demoModal" and starts hidden.
modal-dialog positions the box, and modal-content is the white panel.
- Any element with
data-bs-dismiss="modal" closes the modal.
Result
Clicking the button dims the page and shows a white dialog in the top center with a title, text and two buttons.
Sizes and Position
Class on .modal-dialog | Effect |
modal-sm | Small |
modal-lg | Large |
modal-xl | Extra large |
modal-fullscreen | Full screen |
modal-dialog-centered | Vertically centered |
modal-dialog-scrollable | Body scrolls if content is long |
Static Backdrop
By default, clicking outside the modal closes it. To force the user to use a button, add these attributes:
html
<div class="modal fade" id="confirmModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
Open a Modal with JavaScript
javascript
const modalElement = document.getElementById('demoModal');
const myModal = new bootstrap.Modal(modalElement);
myModal.show(); // open
myModal.hide(); // close
// Listen to events
modalElement.addEventListener('hidden.bs.modal', () => {
console.log('Modal was closed');
});
Common Mistakes
- Placing the modal HTML inside another element with
position: relative, which can cause display problems. Put modals near the end of <body>
- Using the same id for two modals
- Forgetting the JS bundle
Good practice: Use modals sparingly. Too many popups annoy visitors, especially on mobile.
Conclusion
Modals are great for focused tasks. Remember the three parts (header, body, footer) and connect the button and modal with the same id.
Quick Summary: data-bs-toggle="modal" and data-bs-target open a modal. Use modal-dialog options for size and position, and JS for advanced control.