【问题标题】:How do I remove the extra space on the right side of this bootstrap 4 modal?如何删除此 bootstrap 4 模态右侧的多余空间?
【发布时间】:2020-06-17 12:27:25
【问题描述】:

这里是小提琴: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;
}

模态框右侧有一些额外的空间。我不想要那个空间。我希望模态适合内容,即图像。我一直盯着这个太久了,希望能提供任何帮助。

【问题讨论】:

    标签: html css bootstrap-4 bootstrap-modal


    【解决方案1】:

    Bootstrap 正在这样做:

    .modal-dialog {
      max-width: 500px;
    }
    
    • .modal-dialog 元素是块元素,因此希望默认为 100% 宽度,但 Bootstrap 的样式将其保持为 500 像素宽。
    • 您明确将图像设置为 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/


    最后,.gallery { overflow-y: auto } 不会有任何效果,除非您在该元素上指定 heightmax-height

    【讨论】:

    • 谢谢@simmer - 我选择了第二种方法。效果很好!
    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2015-02-01
    • 2012-10-24
    • 2012-02-22
    相关资源
    最近更新 更多