如何在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
相关产品推荐
相关产品推荐

