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%;
}
                Change the size of the modal by adding the . modal-sm class for small modals, . modal-lg class for large modals, or . modal-xl for extra large modals.
Making your Modal Responsive The most obvious way is to write a bunch of media queries like a chump. I instead suggest using max-width and max-height. When combined with calc() this allows you to have a consistent padding between the modal and the edge of the screen on smaller devices.
inline-block elements get dynamic width regarding their content.
body .modal-dialog { /* Width */
    max-width: 100%;
    width: auto !important;
    display: inline-block;
}
Note: width: auto !important; is required to overwrite bootstrap css.
Finally to place it in middle of viewport you to display: flex; on the parent element
.modal {
  z-index: -1;
  display: flex !important;
  justify-content: center;
  align-items: center;
}
.modal-open .modal {
   z-index: 1050;
}
                        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;
}
                        @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;
}
                        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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With