使用Bootstrap调整图像大小以适应div

125

我想让一张图片适应一个指定大小的div。不幸的是,图片没有符合要求,而是按比例缩小到了一个不够大的尺寸。我不确定最好的方法是什么来使图片适应这个div。

如果这不是足够的代码,我很乐意提供更多,并且我也愿意纠正我所忽视的任何其他错误。

以下是HTML:

<div class="span3 top1">  
        <div class="row">
          <div class="span3 food1">
              <img src="images/food1.jpg" alt="">
          </div>
        </div>
            <div class="row">
              <div class="span3 name1">
                  heres the name
            </div>
            </div>
          <div class="row">
              <div class="span3 description1">
                  heres where i describe and say "read more"
            </div>
            </div>


      </div>

我的CSS

.top1{

    height:390px;
    background-color:#FFFFFF;
    margin-top:10px;


}

.food1{

background-color:#000000;
height:230px;


}

.name1{

background-color:#555555;
height:90px;

}

.description1{

background-color:#777777;
height:70px;


}

我在这里发布了对类似问题的答案: https://dev59.com/N1gR5IYBdhLWcg3wAJT7#60279806 - FredyWenger
8个回答

223

尝试这种方式:

<div class="container">
    <div class="col-md-4" style="padding-left: 0px;  padding-right: 0px;">
        <img src="images/food1.jpg" class="img-responsive">
    </div>
</div>

更新:

在Bootstrap 4中,img-responsive变为img-fluid,所以使用Bootstrap 4的解决方案是:


<div class="container">
    <div class="col-md-4 px-0">
        <img src="images/food1.jpg" class="img-fluid">
    </div>
</div>

6
好的!class="img-responsive" 有帮助。也许今天应该接受这个答案。 - Anupam
1
class="img-responsive" 绝对是最好的选择!这应该被接受的答案。 - iMobaio

63

您可以明确定义图像的宽度高度,但结果可能不是最好看的。

.food1 img {
    width:100%;
    height: 230px;
}

jsFiddle


根据您的评论,您也可以阻止任何overflow - 请参见此示例以查看由于宽度过大而被限制高度并被切断的图像。

.top1 {
    height:390px;
    background-color:#FFFFFF;
    margin-top:10px;
    overflow: hidden;
}

.top1 img {
    height:100%;
}

我研究了一下,不幸的是像你所说的那样,结果并不是最好的。理想情况下,我希望将图像缩小,使其高度适合div的高度,并隐藏超出约束div宽度的图像宽度。如果这有意义的话。 - smilefreak24
另一个答案是最好的,只需将class="img-responsive"添加到img标签即可解决问题! - iMobaio
1
更好的替代 width:100%;max-width:100%;,而更好的做法是在BS3中使用类 img-responsive 或在BS4中使用类 img-fluid - Nabi K.A.Z.

62

4
"img-fluid" 就可以了!谢谢! - pyano

36

只需在img标签中添加类img-responsive,它适用于Bootstrap 3及更高版本!


抱歉,能否请您具体说明一下?我没有完全理解您的问题。谢谢! - Shashi

8
我使用了这个方法,对我很有效。
<div class="col-sm-3">
  <img src="xxx.png" style="width: auto; height: 195px;">
</div>

7

我曾经遇到过同样的问题,后来发现以下简单的解决方法。只需要给图片添加一点补白,它就可以自动调整大小以适应div框。

<div class="col-sm-3">
  <img src="xxx.png" class="img-responsive" style="padding-top: 5px">
</div>

1
使用Bootstrap解决,而不是自定义CSS。谢谢。 - mattgreen

6

如果您正在寻找 Bootstrap-4,那么这里就有了。

<div class="row no-gutters">
    <div class="col-10">
        <img class="img-fluid" src="/resources/img1.jpg" alt="">
    </div>
</div>

如果您的另一列中也有文本,那么这并不是理想的解决方案,因为它也会紧贴边框的边缘。 - James Burke

2
大多数情况下,Bootstrap项目使用jQuery,因此您可以使用jQuery。只需使用JQuery.offsetHeight()JQuery.offsetWidth()获取父元素的宽度和高度,并使用JQuery.width()JQuery.height()将它们设置为子元素的宽度和高度。如果您想要使其响应式,请在$(window).resize(func)中重复上述步骤。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接