Open In App

How to Align Modal to Center of the Screen in Bootstrap?

Last Updated : 09 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Aligning a modal to the center of the screen in Bootstrap means positioning the modal window vertically and horizontally at the center of the viewport. This can be achieved using Bootstrap's classes like modal-dialog-centered, which ensures the modal appears in the middle, providing a balanced and user-friendly design.

Approach:

  • Bootstrap Setup: Load Bootstrap 5's CSS/JS via CDN for styling and enabling modal functionalities.
  • Modal Trigger: Open the modal with a button with data-bs-toggle and data-bs-target attributes.
  • Centering the Modal: Add a modal-dialog-centered class to align the modal in the center of the screen vertically.

Example: In this example, we are following the above-explained approach.

html
<!DOCTYPE html>
<html lang="en">

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

<body class="text-center p-4 m-4">

    <!-- Button to trigger modal -->
    <button class="btn btn-primary" 
            data-bs-toggle="modal" 
            data-bs-target="#infoModal">
        Open Modal
    </button>

    <!-- Modal -->
    <div class="modal fade" id="infoModal">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    This is acentered model.
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" 
                            data-bs-dismiss="modal">
                            Close
                    </button>
                </div>
            </div>
        </div>
    </div>

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

</body>

</html>
</html>

Output:

GIF

Similar Reads