如何使用Bootstrap调整图片大小

19

我有一个关于产品的网站。每篇产品文章都包含文本和一些图片。这些图片的宽度从 400 像素到一些达到 700 像素不等。产品文章存储在 SQL Server 数据库中,并根据产品 ID 动态获取文章。

我正在使用 Bootstrap 使我的网站适用于移动设备。我采用了两列布局。产品文章包含在一个带有

标记的 Div 中。

 class="col-md-12 row"
当我缩小页面的大小以预览在移动设备上的显示效果时,文本会很好地自适应,但图像不会。现在我大约有3000个这样的图像,如果有一个属性必须应用于每个单独的图像标签,那将是不可行的。
是否有其他方法可以使用CSS或Bootstrap或JavaScript在设备大小下减小图像的大小,同时保持图像宽高比?
6个回答

32

只需将以下代码添加到您的样式表中,它将应用于您网站上所有的图像。

img {
  display: block;
  max-width: 100%;
  height: auto;
}

汤姆说得非常到位。感谢你分享你的知识。 - Hitz
使用Bootstrap 5版本非常顺畅。谢谢Tom! - betterluckchuck
我会加入的。谢谢,汤姆!xD - Sergo

14

Bootstrap v3及以下版本。

在图像标签中使用class="img-responsive"。这将根据屏幕大小自动调整其大小。这是一个Bootstrap类。

例如:http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_img_responsive&stacked=h

Bootstrap v4

在图像标签中使用class="img-fluid"。这将根据屏幕大小自动调整其大小。这是一个Bootstrap类。更多细节请参见下面的注释。


谢谢您的回答,但我在帖子中提到我有3000多张图片。逐个为这些图片添加这个类将是不可行的。 - Hitz
你可以在DOM准备就绪后使用JavaScript/jQuery添加此属性。 - user2024285
在这种情况下,只需使用通用选择器 img { width: 100% }。 - Alexander Solonik
4
Bootstrap v4将img-responsive重命名为img-fluid。 - Richard Paul

4

使用特定宽度:

<img src="assets/img/why1.png" style="max-width:20%;" alt="...">

自动宽度:

<img src="assets/img/why2.png" class="img-fluid" alt="...">

2

试试这个。

<div class="row">
<div class="col-md-4">
    <img class="thumbnail img-responsive" src="h.jpg" />
</div>
</div>

1
Bootstrap 3 ➜ 4 迁移,img-responsive 已被更名为 img-fluid。https://getbootstrap.com/docs/4.1/migration/#images - Joe Sadoski

0
尝试将此添加到CSS中。
.col-md-12 img {width:100%}

0

 #imgdiv { width:40vw;display:table-cell;vertical-align:middle; text-align:center;}
img {max-width:100%;height:auto;max-height:100%;}
<div class="row">
  <div id="imgdiv" class="col-sm-5 text-center">
        <img class="thumbnail img-responsive"  src="https://images.pexels.com/photos/736230/pexels-photo-736230.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" 
            style="maxwidth:100%;height: auto;max-height: 100%;"> 
 </div>
</div>


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