How do I remove the extra space on the right side of this bootstrap 4 modal?

Viewed 762

Here is the fiddle: https://jsfiddle.net/apo5u0mt/

Here is the code:

HTML

<div class="modal" id="galleryModal">
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
    <div class="modal-content">
      <div class="gallery">
        <div class="gallery-item">
          <img src="https://preview.ibb.co/kPE1D6/clouds.jpg">
        </div>
        <div class="gallery-item">
          <img src="https://preview.ibb.co/mwsA6R/img7.jpg">
        </div>
        <div class="gallery-item">
          <img src="https://preview.ibb.co/kZGsLm/img8.jpg">
        </div>
      </div>
    </div>
  </div>
</div>

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

CSS

.gallery {
  overflow-y: auto !important;
}

.gallery-item {
  margin: 5px;
  float: left;
}

.gallery-item img {
  height: 150px;
  width: 200px;
  object-fit: cover;
}

.btn {
  margin: 5px;
}

There is some extra space on the right side of the modal. I do not want that space. I want the modal to fit the contents, which are images. I have been staring at this for entirely too long, and would appreciate any help.

1 Answers

Bootstrap is doing this:

.modal-dialog {
  max-width: 500px;
}
  • The .modal-dialog element is a block element, and thus wants to be 100% width by default, but Bootstrap's styling is keeping it to 500px wide.
  • You're explicitly setting your images to be 200px wide each, which (ignoring margins for the moment) only adds up to 400px.


Two possible fixes are:

1. Override Bootstrap's modal styling here to constrain the modal to a narrower width:

/*
  The value below is empirically tested,
  allows for your given margins & floating. I originally expected it to be
  420px = (200px width + 5px left margin + 5px right margin) * 2
  but 422px was necessary to avoid wrapping when tested in jsfiddle
*/

.modal-dialog {
  max-width: 422px;
}

https://jsfiddle.net/nftj9s7y/1/

If images being exactly 200px wide is what matters, then that's your solution. However, that seems like a brittle solution to me - it'll break if you decide to change image widths, and might not work at smaller screen sizes.


The more flexible solution would be:

2. Use flexbox to have images expand to fill the modal

.gallery {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
}

/* now that the parent element is display: flex, we don't need floats anymore */
.gallery-item {
  padding: 5px;
  width: 50%;
}

.gallery-item img {
  height: 150px;
  object-fit: cover;
  width: 100%; /* allow image to fill width of containing element */
}

https://jsfiddle.net/vzs98n6b/2/


And as a final note, .gallery { overflow-y: auto } won't have any effect unless you specify a height or max-height on that element.

Related