'Bootstrap Modal Dynamic Width

I am trying to define a bootstrap modal that gets a dynamic width regarding its content and if necessary a vertical scrollbar.

The vertical scrollbar works but the horizontal width seems to be a fixed width. Could you please help?

Modal:

<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h4 class="modal-title">Dynamic Modal Title</h4></div>
      <div class="modal-body">Dynamic Modal Body</div>
      <div class="modal-footer">Dynamic Modal Footer</div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

CSS:

.modal .modal-body { /* Vertical scrollbar if necessary */
    max-height: 480px;
    overflow-y: auto;
}

body .modal-dialog { /* Width */
    max-width: 100%;
}


Solution 1:[1]

@tmg's answer will only work for Bootstrap 3. For Bootstrap 4, use this:

.modal {
    text-align: center;
}

Alongside his suggestion:

.modal-dialog {
    text-align: left; /* you'll likely want this */
    max-width: 100%;
    width: auto !important;
    display: inline-block;
}

Solution 2:[2]

fit-content worked well for me with no ill side effects like a misplaced modal.

.modal {
    padding: 1%;
}
.modal-lg {
    min-width: auto;
    max-width: fit-content;
}

Solution 3:[3]

Works in Bootstrap 4-

Here I have added min width to 300px, max width to 90vw, modal can be scrolled vertically using screen scrollbar, and horizontal scrollbar shows up on modal if content width is > 90vw

.modal-dialog {
  position: relative;
  display: table;
  overflow: auto;
  width: auto;
  min-width: 300px;
}
.modal-body { /* Restrict Modal width to 90% */
  overflow-x: auto !important;
  max-width: 90vw !important;
}

Solution 4:[4]

I only needed it for modal-lg and modal-xl. Here is how I fixed it:

@media (min-width: 576px) {
  .modal-dialog.modal-xl{
    max-width: min( 90vw, 1200px ) !important;
  }
  .modal-dialog.modal-lg{
    max-width: min( 90vw, 900px ) !important;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vael Victus
Solution 2
Solution 3 Shantanu Mahakale
Solution 4 chickens