Centering Bootstrap modal in wide pages

Viewed 21

On mobile devices, Bootstrap modal is not centered correctly when the page is wider than 980px, leaving white space on the right of the screen.

I dont want to use meta viewport which will zoom the page in as I need the full width to show on mobile devices.

The snippet bellow is using Bootsrap 5. I tried 3 and 4 too.

You can see in the screenshot that the modal div is positioned out of the screen and the backdrop doesn't cover the full width, leaving white space on the right and also pushes page content (the button) to the left.

enter image description here <-- invisible whitespace in image

You can see it here with a phone or using chrome mobile device mode

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

<head>
  <meta charset="UTF-8">
  <title>Document</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
    integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
    crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8"
    crossorigin="anonymous"></script>

</head>

<body class="text-center">
  <style>
    body {
      width: 1035px;
    }

    #open-button {
      font-size: 32px;
    }
  </style>

  <!-- Button trigger modal -->
  <button id="open-button" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
    Launch demo modal
  </button>

  <div>
    <img src="https://via.placeholder.com/1024" alt="">
  </div>
  <!-- Modal -->
  <div class="modal fade mx-auto" 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">
          ...
        </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>

</body>

</html>

0 Answers
Related