如何删除这个bootstrap 4模态右侧的多余空间



这是小提琴:https://jsfiddle.net/apo5u0mt/

这是代码:

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;
}

模态的右侧有一些额外的空间。我不想要那个空间。我希望模态适合内容,即图像。我已经盯着这个看了太久了,如果有任何帮助,我将不胜感激。

Bootstrap正在执行以下操作:

.modal-dialog {
max-width: 500px;
}
  • .modal-dialog元素是一个块元素,因此默认情况下希望为100%宽,但Bootstrap的样式将其保持为500px宽
  • 您明确地将每个图像设置为200像素宽,这(暂时忽略边距(加起来只有400像素


两种可能的修复方法是:

1.在此处覆盖Bootstrap的模态样式,以将模态约束为较窄的宽度:

/*
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/

如果图像宽度恰好为200像素才是最重要的,那么这就是您的解决方案。然而,对我来说,这似乎是一个脆弱的解决方案——如果你决定改变图像宽度,它就会崩溃,而且在较小的屏幕尺寸下可能无法工作。


更灵活的解决方案是:

2.使用flexbox展开图像以填充模态

.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/


最后要注意的是,除非在该元素上指定heightmax-height,否则.gallery { overflow-y: auto }不会有任何效果。

最新更新