如何使用Bootstrap类设置HTML中图片的宽高?相关类有哪些?
替代行内样式用Bootstrap类设置图片宽高的方案
问题原文
我在HTML页面的
标签内添加了标签,目前通过行内style设置图片宽高为200px×200px,希望使用Bootstrap类替代行内样式实现图片宽高设置,请问具体该如何操作?以下是我的代码:
<div class="col"> <div class="card border border-2 border-danger w-75 mt-3"> <img src="/Images/oppo-a31-2020-128-gb-black-6-gb-ram-.jpg" class="mx-auto d-block img-fluid" style="height:200px; width:200px;" alt="xxx"> <div class="card-body text-center"> <h5 class="card-title">Oppo A13</h5> <p class="card-text" >Our Price: To see product details, add this item to your cart. You can always remove it later.</p> <a href="#" class="btn btn-primary">Buy Now</a> </div> </div> </div>
具体操作方法
Bootstrap默认没有提供固定200px宽高的内置类,最直接的方式是自定义CSS类来实现,同时遵循Bootstrap的样式管理规范:
- 添加自定义CSS类
在你的样式文件或页面的<style>标签中定义如下类:
.img-square-200 { width: 200px; height: 200px; }
- 修改img标签的class属性
移除行内的style="height:200px; width:200px;",将自定义类加入到class列表中:
<img src="/Images/oppo-a31-2020-128-gb-black-6-gb-ram-.jpg" class="mx-auto d-block img-fluid img-square-200" alt="xxx">
- 可选:优化图片显示比例
如果你的图片不是1:1比例,可搭配Bootstrap的object-fit类避免拉伸变形:
<!-- 裁剪图片填充容器,保持比例 --> <img src="/Images/oppo-a31-2020-128-gb-black-6-gb-ram-.jpg" class="mx-auto d-block img-fluid img-square-200 object-fit-cover" alt="xxx"> <!-- 完整显示图片,容器内留空白 --> <img src="/Images/oppo-a31-2020-128-gb-black-6-gb-ram-.jpg" class="mx-auto d-block img-fluid img-square-200 object-fit-contain" alt="xxx">
内容的提问来源于stack exchange,提问作者Farhana
相关产品推荐
相关产品推荐

