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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:07