首页 > 解决方案 > Can't get image to stay within div in Bootstrap 4

问题描述

I'm having trouble getting an image to conform to the size of the div. I'm using Bootstrap 4.1.3.

I'm attempting to create a row that has two side by side columns, with text in one column and an image in the other. I'd like to keep the row "above the fold" for a 1366x768 resolution, and so I've constrained the row to 500px high. The problem is that my image is 344 × 690 and won't shrink to fit the row. It simply overflows top and bottom.

Here is the code:

<div class="special-background">
   <div class="container-fluid">  
      <div class="row py-4 bg-p1" style="height: 500px">
          <div class="col-lg-6 d-flex align-items-center text-white">
            <p class="display-4 pl-4">Lorem ipsum dolor sit amet</p>
          </div>

          <div class="col-lg-6 p-4 d-flex align-items-center">
            <img src="../imgs/image-name.png" class="img-fluid" alt="Responsive image">
          </div>

      </div>
    </div>
</div>

.img-fluid is defined in bootstrap 4 like so:

.img-fluid {
max-width: 100%;
height: auto;
}

I've tried changing height to 100%, but then it stretches like crazy at different viewport sizes.

标签: bootstrap-4

解决方案


由于您有一个静态的行高度,因此您必须设置height: 100%为内部 cols,然后设置max-height: 100%为 image 和width: auto,以便不被拉伸。也设置margin: auto为始终居中。

代码:

.special-background .row > div {
 height: 100%;
}

.img-fluid {
 max-heihgt: 100%;
 width: auto;
 margin: auto;
}

推荐阅读