Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Bootstrap Modal: The Complete Guide to Responsive Modals

Have you ever visited a website and noticed content overlayed on the web page? That’s an example of a modal on a website. They help you to direct user attention to a particular element or notification on your page.

If your website uses Bootstrap and you’d like to add this type of popup to your site, then you’ve come to the right place.

In this tutorial, we’ll explain what Bootstrap modal means and discuss some of the benefits of using it on your website. Then we’ll discuss the components of a modal and show you how to create Modals in Bootstrap. Let’s begin.

What Is Bootstrap Modal?

A Bootstrap Modal is a lightweight, flexible, and responsive JavaScript popup or dialog box that is part of the Bootstrap framework. It is designed to overlay content on a website, creating a temporary and focused area for displaying additional information, forms, or interactive components without navigating to a new page.

Benefits of Using Modals on Your Site

There are many benefits to using modals on a website. Below we’ll explain a few of them:

  1. User Engagement: Modals can capture users’ attention by presenting important information or interactive elements in a visually appealing way.

  2. Space Efficiency: Modals allow you to display additional content without cluttering the main page. This is especially beneficial for forms, login boxes, or secondary information.

  3. Improved User Flow: Modals keep users within the context of the current page. This eliminates the need for them to navigate away and provides a smoother user experience.

  4. Responsive Design: Bootstrap Modals are designed to be responsive, ensuring that they adapt well to various screen sizes. This makes them suitable for mobile devices and desktops alike.

Speaking of responsive web design practice, PureCode provides customizable components to help you build responsive web pages faster. This reduces the time to build repetitive templates and lets you focus on defining the logic for your web application.

Get Started With PureCode

Getting Started with Bootstrap Modal

Prerequisites

Before you get started, you’ll need basic HTML and CSS knowledge. You’ll also need to have some knowledge of how Bootstrap works. Please see the video below to learn about using Bootstrap for web development.

Installation and Setup

There are 2 ways to add Bootstrap to a web project: Downloading the necessary files from https://getbootstrap.com/ and adding them to your project’s directory. Alternatively, you can use CDN (Content Delivery Network) to quickly add Bootstrap to your project.

For this tutorial, we’ll use the CDN method. To do so, you’ll need to add the Bootstrap CSS bundle to your HTML template. Copy and paste the code below to your HTML file. The code should be placed between the opening and closing <head> tag.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

After adding the CSS file, you’ll need to also include Bootstrap’s JS bundle. This package is essential as it includes some JavaScript functions required for components like the modal to work properly. The code should be placed just above the closing body tag (</body>) on your template.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

Now that we’ve added the necessary files for Bootstrap, let’s create a simple modal and explain each component.

Creating a Simple Modal

To create a modal in Bootstrap, you need to set up 2 elements on your page. The first is the modal trigger element, which can be a button or an anchor link. The second element is the actual modal which comprises a header, body, footer, and other components like the close button. Here is an example of a basic implementation of a modal in Bootstrap.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Bootstrap Modal Example</title>
</head>
<body>

<div class="container mt-5 col-md-8">
    <h2>Bootstrap Modal Example</h2>

    <!-- Trigger Button -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
        Open Modal
    </button>

    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal Title</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>This is the content of the modal. You can add any HTML or components 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>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

In the code above:

  • The modal is triggered by a button with the data-bs-toggle and data-bs-target attributes.

  • The modal itself is represented by a div with the class modal. It has a unique ID (exampleModal) and includes three main sections: modal-dialog, modal-content, and the actual content inside the modal-body.

  • The modal contains a title (modal-title), a close button (btn-close), content in the body, and optional footer buttons.

  • The close button in the modal header has the attribute data-bs-dismiss=”modal”, which allows users to close the modal.

  • Optional footer buttons can perform specific actions when clicked.

This example provides a basic template for creating a Bootstrap modal. Here is how it looks when you preview your webpage.

Bootstrap Modal Components

A Bootstrap modal consists of several components that work together to create a popup dialog box. Below, we’ll explain each component along with the classes for each section:

1. Modal Container (<div class=”modal”>): This is the outermost container that wraps all the modal components. It contains the modal’s ID, tabindex, and aria-labelledby/aria-hidden attributes.

<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <!-- Other modal components go here -->
</div>

2. Modal Dialog (<div class=”modal-dialog”>): This represents the main dialog box within the modal. This section can have additional classes like modal-dialog-centered for centering the modal vertically.

<div class="modal-dialog">
  <!-- Modal content goes here -->
</div>

3. Modal Content (<div class=”modal-content”>): Contains the actual content of the modal, including the header, body, and footer. The content box is styled using Bootstrap classes.

<div class="modal-content">
  <!-- Modal header, body, and footer go here -->
</div>

4. Modal Header (<div class=”modal-header”>): This section contains the title and an optional close button. The title is typically marked with the modal-title class. The close button can be added with the btn-close class and data-bs-dismiss=”modal” attribute.

<div class="modal-header">
  <h5 class="modal-title" id="exampleModalLabel">Modal Title</h5>
  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>

5. Modal Body (<div class=”modal-body”>): The modal body section holds the main content of the modal. You can add any HTML content or other Bootstrap components like tooltips and popovers.

<div class="modal-body">
  <p>This is the content of the modal.</p>
</div>

6. Modal Footer (<div class=”modal-footer”>): This section contains buttons or other elements that perform actions (e.g., Close, Save). It is styled using Bootstrap classes like btn for buttons.

<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>

7. Trigger Button: The button or link that triggers the modal to open. It uses attributes like data-bs-toggle and data-bs-target to specify which modal to open.

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
  Open Modal
</button>

Advanced Modal Configurations

Now that we’ve learned the basics of setting up a modal in Bootstrap. Let’s cover some advanced concepts like changing modal sizes, centering, and scrollable modal examples.

Different Modal Sizes

Bootstrap provides options for different modal sizes to accommodate varying content. The modal-lg and modal-sm classes can be used for large and small modals, respectively.

These additional classes should be added next to the modal-dialog class. If you don’t specify a size class, the default modal size will be applied to the modal. Here is an example of a small and large modal.

<!-- Large Modal -->
<div class="modal fade" id="largeModal" tabindex="-1" aria-labelledby="largeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <!-- Modal content goes here -->
    </div>
  </div>
</div>

<!-- Small Modal -->
<div class="modal fade" id="smallModal" tabindex="-1" aria-labelledby="smallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <!-- Modal content goes here -->
    </div>
  </div>
</div>

Below is a table showing the available sizes Bootstrap supports along with their max width.

SizeClassModal Max Width
Small.modal-sm300px
DefaultNone500px
Large.modal-lg800px
Extra largemodal-xl1140px

Modal Variations

Aside from modifying the size of the modal, there are other modal variations you can implement to customize your popups. Modal variations in Bootstrap provide different ways to use and display modals, catering to various design and functionality needs. Here are some common modal variations:

Centered Modal: To center a modal vertically, add the modal-dialog-centered class to the modal-dialog.

<div class="modal-dialog modal-dialog-centered">
  <!-- Modal content goes here -->
</div>
vertically centered modal

Scrollable Modal: When your modal content is long, making the modal scrollable is beneficial. To do so, use the modal-dialog-scrollable class. This ensures the modal content scrolls through the container without overflowing on the user’s viewport.

<div class="modal-dialog modal-dialog-scrollable">
  <!-- Modal content goes here -->
</div>

Fullscreen Modal: A fullscreen modal in Bootstrap is a type of modal dialog box that covers the entire screen. This can be particularly useful for ensuring that a user’s attention is focused on the content of the modal, such as forms, information, or interactive content. To make the modal fullscreen, add the modal-fullscreen class to the modal-dialog div.

<div class="modal-dialog modal-fullscreen">
  <!-- Modal content goes here -->
</div>

Static Backdrop: Normally, clicking outside the modal closes it. But with a static backdrop (using data-bs-backdrop=”static”), clicking outside the modal won’t dismiss it. This is useful for modals where user interaction inside the modal is required.

Handling Multiple Modals

If your page needs to handle multiple modals, ensure each modal has a unique ID. To prevent conflicts, set the data-bs-target attribute in your trigger buttons.

<!-- Trigger buttons -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal1">Open Modal 1</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal2">Open Modal 2</button>

<!-- Modals -->
<div class="modal fade" id="modal1" tabindex="-1" aria-labelledby="modal1Label" aria-hidden="true">
  <!-- Modal content goes here -->
</div>

<div class="modal fade" id="modal2" tabindex="-1" aria-labelledby="modal2Label" aria-hidden="true">
  <!-- Modal content goes here -->
</div>

Remember to ensure that each modal ID is unique. You can open and manage multiple modals using JavaScript/jQuery if needed.

Styling and Customization

Bootstrap provides a solid foundation for responsive modals out of the box. However, you might want to customize the appearance to match your specific design requirements. In this section, we’ll explore various aspects of styling and customization for Bootstrap modals.

Customizing Modal Styles

Bootstrap allows you to customize modal styles using custom CSS or with Bootstrap’s utility classes. Here are some common customization options:

Background Color: This controls the background of the modal container. You can change the background color of the modal using the bg-* classes. For example:

<div class="modal-content bg-primary">
  <!-- Modal content goes here -->
</div>

Text Color: This controls the color of text elements in the modal HTML container. You can adjust the text color inside the modal using text-* classes. For example:

<div class="modal-content text-light">
  <!-- Modal content goes here -->
</div>

Theming Modal Components in Bootstrap

Bootstrap also allows you to customize the appearance of specific parts of the modal, such as the header, body, and footer, to match your design preferences. Bootstrap provides a set of utility classes and predefined styles that you can use for theming. Below, we’ll explain how to theme each component individually:

Theming Modal Header

Customizing the modal header involves adjusting the background color, text color, and other styles. Here’s an example:

<div class="modal-header bg-primary text-white">
  <h5 class="modal-title">Modal Title</h5>
  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>

In this example, the bg-primary class sets the background color to the primary color, and text-white sets the text color to white.

Theming Modal Body

Customizing the modal body allows you to style the content area. You can use custom classes or Bootstrap utility classes for styling. For example:

<div class="modal-body custom-body">
  <!-- Body content goes here -->
</div>

In this case, the custom-body class can be defined in your custom CSS to apply specific styles to the modal body.

Theming Modal Footer

Customizing the modal footer involves styling the buttons or any other content in the footer. Here’s an example:

<div class="modal-footer bg-dark text-white">
  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
  <button type="button" class="btn btn-primary">Save changes</button>
</div>

In this example, the bg-dark class sets the background color to a dark shade, and text-white sets the text color to white.

JavaScript Events and Callbacks

JavaScript events and callbacks play a crucial role in managing Bootstrap modals, enabling dynamic interactions and responses in web applications. Here’s an in-depth look at how these elements work.

Opening and Closing Modals Programmatically

To interact with a Bootstrap modal via JavaScript, you can use functions to open or close the modal, without the need for user interaction such as clicking a button.

Opening a Modal Programmatically: To open a Bootstrap modal with JavaScript, you typically use the .modal(‘show’) method. Here’s an example:

// Assuming you have a modal with an ID of 'myModal'
$('#myModal').modal('show');

This code selects the modal element by its ID and then calls the .modal(‘show’) method, which opens the modal.

Closing a Modal Programmatically: Similarly, to close the modal, you use the .modal(‘hide’) method:

$('#myModal').modal('hide');

Handling Modal Events

Bootstrap modals come with several events that allow you to run specific code in response to user interactions or modal state changes. These events include:

  • show.bs.modal: This event fires immediately when the show instance method is called.

  • shown.bs.modal: Fired when the modal has been made visible to the user.

  • hide.bs.modal: This event is fired immediately when the hide instance method has been called.

  • hidden.bs.modal: Fired when the modal has finished being hidden from the user.

Here’s an example of how to use these events:

$('#myModal').on('shown.bs.modal', function () {
  console.log('Modal is fully shown');
});

$('#myModal').on('hidden.bs.modal', function () {
  console.log('Modal is fully hidden');
});

In this example, when the modal is completely shown, the message “Modal is fully shown” is logged to the console. Similarly, when the modal is completely hidden, “Modal is fully hidden” is logged.

Creating Bootstrap Modals in React

If you’re using React for your web application, you can easily integrate Bootstrap using the react-bootstrap library. To do so, you’ll first need to install the React-bootstrap library to your project.

npm install react-bootstrap bootstrap

Then, import Bootstrap’s CSS in your main JavaScript file (typically index.js or App.js):

import 'bootstrap/dist/css/bootstrap.min.css';

Now let’s create a functional component for our modal element. This component can accept props to control its visibility and content. For this example, we’ll name our component MyModal.js but you can use any name you like.

import React from 'react';
import { Modal, Button } from 'react-bootstrap';

function MyModal({ show, handleClose, title, children }) {
  return (
    <Modal show={show} onHide={handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>{title}</Modal.Title>
      </Modal.Header>
      <Modal.Body>{children}</Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={handleClose}>
          Close
        </Button>
      </Modal.Footer>
    </Modal>
  );
}

export default MyModal;

We can now import the new component we just created to our App.js file to create a modal. You’ll need to manage its visibility using state in the parent component. Here is the code to add to your App.js file.

import React, { useState } from 'react';
import { Button } from 'react-bootstrap';
import MyModal from './MyModal'; // Import your modal component

function App() {
  const [modalShow, setModalShow] = useState(false);

  const handleClose = () => setModalShow(false);
  const handleShow = () => setModalShow(true);

  return (
    <div>
      <Button variant="primary" onClick={handleShow}>
        Launch Modal
      </Button>

      <MyModal show={modalShow} handleClose={handleClose} title="My Modal">
        <p>This is the content of the modal</p>
      </MyModal>
    </div>
  );
}

export default App;

In this example, modalShow is a state variable that determines whether the modal is shown or not. The handleClose and handleShow event handlers are used to update this state, effectively controlling the modal’s visibility.

To learn more about using modals in Bootstrap, check out the video below.

Troubleshooting Common Issues

Troubleshooting and resolving common issues in Bootstrap modals is crucial for ensuring a smooth user experience. Below, we’ll discuss some common issues you might encounter with Bootstrap modals, including their potential causes and solutions.

Modal not Opening/Closing

This issue can occur when a modal does not open or close as expected. The problem might be due to JavaScript errors, conflicts in event handling, or incorrect use of Bootstrap’s modal methods. Below are some of the common causes and solutions.

  1. JavaScript Errors: Check for JavaScript errors in the console. A JavaScript error elsewhere in your script can prevent the modal-related code from executing.

  2. Incorrect Selector or Typo: Ensure that the ID or class used in your jQuery selector matches the modal’s ID or class.

    // Make sure the selector matches the modal's ID
    $('#myModal').modal('show');
  3. Event Handling Conflicts: Make sure you’re not preventing the default action on buttons or links that trigger the modal.

    $('#myButton').on('click', function(e) {
      e.preventDefault();  // Make sure this isn't preventing the modal from opening
      $('#myModal').modal('show');
    });

Styling Conflicts

Styling conflicts can occur when your CSS styles override or conflict with Bootstrap’s default modal styles. Here are some of the common causes and solutions.

  1. CSS Overrides: Ensure that your custom CSS does not unintentionally override modal styles. Use browser developer tools to inspect the modal elements and identify any overriding styles.

  2. Class Naming Conflicts: Avoid using common class names that might conflict with Bootstrap’s classes. You can prefix your class names with a unique identifier.

Z-index Issues

Z-index issues arise when the modal is improperly layered in the document, causing it to appear behind other elements. Below are some of the common causes and solutions.

  1. Incorrect Z-index Values: Ensure that the modal’s z-index is higher than other page elements. You can increase it using custom CSS.

    .modal {
      z-index: 1050; /* Increase if necessary */
    }
  2. Nested Elements: Avoid nesting modals within elements that have a lower z-index. Modals should typically be a direct child of the <body> tag.

    <body>
      <!-- Other content -->
      <div class="modal" id="myModal">...</div>
    </body>
  3. Stacked Modals: If using multiple modals, manage their z-index values carefully to ensure they layer correctly.

Best Practices When Creating Bootstrap Modal

When creating modals in Bootstrap, there are some tips to follow to ensure it looks and works properly. Here are a few things to consider.

Accessibility Considerations

  • Use Semantic HTML: Ensure that your modal structure uses semantic HTML elements. Use appropriate heading tags (<h1>, <h2>) for titles and label elements for form controls to enhance accessibility.

  • Keyboard Navigation: Test and ensure that users can navigate through the modal using a keyboard. All interactive elements within the modal should be accessible and focusable.

  • ARIA Roles and Attributes: Leverage ARIA (Accessible Rich Internet Applications) roles and attributes to enhance the accessibility of your modal. For instance, use aria-labelledby to associate a label with the modal.

  • Focus Management: Manage focus properly when the modal is opened and closed. Set the initial focus to the first interactive element within the modal and trap focus inside the modal to prevent users from tabbing outside of it.

Responsive Design Tips

  • Test on Various Devices: Ensure that your modals are responsive by testing them on various devices and screen sizes. Bootstrap provides a responsive design by default, but custom styling or content may impact responsiveness.

  • Media Queries: Utilize media queries in your custom styles if needed. Adjust the modal’s appearance or behavior based on the device width to provide an optimal user experience.

  • Use Bootstrap Grid System: If your modal content requires a grid layout, use Bootstrap’s grid system for responsiveness. It automatically adjusts the layout based on the screen size.

Frequently Asked Questions

These are answers to some of the top questions about creating modals in Bootstrap.

How do I trigger a Bootstrap Modal?

You can trigger a Bootstrap modal using JavaScript or data attributes. To open a modal using JavaScript:

<button type="button" class="btn btn-primary" id="myModalBtn">Open Modal</button>

<script>
  document.getElementById('myModalBtn').addEventListener('click', function () {
    var myModal = new bootstrap.Modal(document.getElementById('myModal'));
    myModal.show();
  });
</script>

Can I have multiple modals on the same page?

Yes, you can have multiple modals on the same page. Each specific modal should have a unique id, and you can trigger them independently using JavaScript or data attributes.

How can I customize the appearance of the modal?

You can customize the appearance of the modal using Bootstrap classes or your custom styles. Bootstrap provides various classes for modal header, body, and footer. You can also use the style attribute or your custom CSS to adjust colors, sizes, and other styles.

What events are available for handling modal actions?

Bootstrap provides several events for handling modal actions, such as show.bs.modal, shown.bs.modal, hide.bs.modal, and hidden.bs.modal. You can use these events to perform actions before or after a modal is shown or hidden.

Are there any known issues with modals on mobile devices?

Bootstrap’s modals are generally mobile-friendly. However, it’s essential to test your modals on different devices to ensure a smooth user experience. Some issues may arise based on your specific implementation and content.

How do you trigger modal open in Bootstrap?

You can trigger modal open using data attributes or JavaScript. The data-bs-target attribute targets the id of the <div> element containing the modal.

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">Open Modal</button>

How to show modal popup on page load in Bootstrap 5?

To show a modal popup on page load in Bootstrap 5, you can use JavaScript:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    var myModal = new bootstrap.Modal(document.getElementById('myModal'));
    myModal.show();
  });
</script>

How to set modal popup in center of the screen?

To set a modal popup in the center of the screen in Bootstrap, you can use the modal-dialog-centered class:

<div class="modal-dialog modal-dialog-centered">
  <div class="modal-content">
    <!-- Modal content goes here -->
  </div>
</div>

Final Thoughts on Using Bootstrap Modal

Bootstrap provides components that make it easy to build most aspects of a website. It also provides advanced components like adding modal dialogs to your site without writing any custom CSS or JavaScript.

In this tutorial, we’ve covered some of the basics of using the Bootstrap modal plugin on a website. Concepts like customizing and triggering the modal via data attributes or JavaScript. We also covered some advanced concepts like customizing the size and position of the modal element.

This should help you get started with creating and using modals to create user notifications in Bootstrap.

If you’re looking to speed up your development time, consider checking out PureCode.ai. PureCode provides over 10k AI-generated templates that can be integrated into your web pages to help you build UI faster.

Further reading:

If this article was helpful, check out our other styling tutorials to improve your skills as a web developer.

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer