Bootstrap4如何调整右侧图片高度匹配左侧内容并保持宽高比
解决方案
Bootstrap 4 的 .row 默认使用 flex 布局,同层级的列天生等高,你只需要调整右侧列和图片的内置类即可去掉硬编码的 200px,同时满足「顶部右对齐、和左侧内容等高、保持宽高比不变形」的需求:
- 给右侧的
.col-sm新增三个 Bootstrap 内置类:d-flex把列设为弹性容器、justify-content-end让内容右对齐、align-items-start让内容贴顶部对齐 - 给
img标签新增两个内置类:h-100让图片高度自动撑满父容器高度(和左侧内容自动等高)、w-auto让宽度自适应,保证宽高比不会被拉伸变形,删除原有的硬编码宽度属性即可
修改后的完整代码如下:
<div class="container"> <div class="row"> <div class="col-sm"> <div class="alert alert-success"> why cannot I still use table for this kind of tasks? why cannot I still use table for this kind of tasks? </div> <div class="alert alert-info"> It is end of 2021 </div> <div class="alert alert-info"> Now I'd updated to div, this contents can have more text </div> </div> <div class="col-sm d-flex justify-content-end align-items-start"> <img class="h-100 w-auto" src="https://www.codeply.com/images/partner_creativetim.png" /> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Larry Cai
相关产品推荐
相关产品推荐

