You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap 5卡片中调整图片大小并设置圆角居中?

解决Bootstrap 5卡片内图片缩小、居中并设置圆角的问题

方法一:用Bootstrap 5内置工具类实现

直接借助Bootstrap自带的类就能快速完成需求,无需额外编写CSS:

  • 用 w-* 系列类控制图片宽度(比如 w-50 表示占父容器50%宽度)
  • mx-auto + d-block 实现图片水平居中
  • rounded-* 类设置圆角(rounded-circle 可直接生成圆形,rounded-4 这类数值类对应不同弧度的圆角)

修改后的完整代码:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
    rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
    crossorigin="anonymous">
    

<div class="container">
        <div class="row justify-content-center">
            <div class="col">
                <div class="card text-center">
                    <!-- 新增mx-auto、d-block、w-50、rounded-4类 -->
                    <img class="d-block mx-auto w-50 rounded-4" src="https://3.imimg.com/data3/LE/LH/GLADMIN-37134/school-badges-500x500.jpg" alt="校徽">
                    <h1 class="text-primary">{{board.school_name}}</h1>
                    <p>{{board.school_address}}, {{board.location}}</p>
                    <p>P O Box: {{board.p_o_box}}</p>
                </div>
            </div>
        </div>
    </div>

可根据需求调整:

  • 宽度:换成 w-25(25%宽度)、w-75(75%宽度)等
  • 圆角:用 rounded-circle 替代 rounded-4 可得到圆形图片

方法二:自定义CSS实现精细化控制

如果需要固定像素尺寸、特殊圆角值这类更细致的设置,可编写自定义CSS:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
    rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
    crossorigin="anonymous">
<style>
  .custom-card-img {
    width: 160px; /* 固定宽度 */
    height: 160px; /* 固定高度,保持正方形比例 */
    object-fit: cover; /* 防止图片拉伸变形 */
    border-radius: 12px; /* 自定义圆角大小 */
    margin: 1.5rem auto; /* 上下外边距+水平居中 */
    display: block;
  }
</style>
    

<div class="container">
        <div class="row justify-content-center">
            <div class="col">
                <div class="card text-center">
                    <img class="custom-card-img" src="https://3.imimg.com/data3/LE/LH/GLADMIN-37134/school-badges-500x500.jpg" alt="校徽">
                    <h1 class="text-primary">{{board.school_name}}</h1>
                    <p>{{board.school_address}}, {{board.location}}</p>
                    <p>P O Box: {{board.p_o_box}}</p>
                </div>
            </div>
        </div>
    </div>
  • object-fit: cover 能保证图片在固定尺寸内按比例裁剪显示,避免拉伸失真
  • 可自行调整 width、height、border-radius 的数值达到预期效果

内容的提问来源于stack exchange,提问作者Adamu Abdulkarim Dee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:05:18