← Back to Bootstrap Course | Chapter 8: Components — Modals & Offcanvas | Lesson 1 of 8

Modal basics

A modal is a dialog that appears on top of the page and blocks interaction until it is closed.

In this page:

  1. Modal basics
Syntax
markup
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal-id">Open</button>

<div class="modal fade" id="modal-id" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">Title</div>
      <div class="modal-body">Body</div>
      <div class="modal-footer">Footer</div>
    </div>
  </div>
</div>

Modal basics

Build a .modal with .modal-dialog, .modal-content, header, body and footer. A button with data-bs-toggle="modal" and data-bs-target opens it, and data-bs-dismiss="modal" closes it.

Add tabindex="-1", aria-labelledby and a title for accessibility.

Requires the JS bundle.

Note: Place the modal markup at the top level of the body to avoid stacking issues.

Example: Modal basics

markup
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body class="p-3">
<div class="container">
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#demoModal">Launch modal</button>
  <div class="modal fade" id="demoModal" tabindex="-1" aria-labelledby="demoTitle" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header"><h5 class="modal-title" id="demoTitle">Modal title</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
        <div class="modal-body">Modal body text goes here.</div>
        <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button class="btn btn-primary">Save changes</button></div>
      </div>
    </div>
  </div>
</div>
</body>
</html>
Live Example
Related Topics
Common Mistakes
  1. Missing target id
  2. Forgetting tabindex and aria attributes
  3. Nesting modals inside fixed elements
Chapter Summary
  • modal, modal-dialog, modal-content
  • data-bs-toggle and data-bs-target open it
  • data-bs-dismiss closes it
  • Needs the JS bundle
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.