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

如何使用Bootstrap5实现子Div在父Div内底部或居中对齐

你当前的代码问题在于承载内容的遮罩层没有设置为弹性容器、也未占满父级高度,内层弹性容器也缺少垂直对齐配置,仅需要调整Bootstrap自带类即可实现需求,无需额外写自定义样式。

需求1:标题和CTA对齐到容器底部

修改两处类即可:

  1. 给class为mask的div新增d-flex flex-column类,让它占满父容器高度,开启弹性布局
  2. 给包裹内容的d-flex justify-content-centerdiv新增w-100 mt-auto类,mt-auto会自动把内容块推到容器底部
    完整修改后代码:
<div
  class="d-flex align-items-stretch mb-3 rounded shadow text-center bg-image img-fluid"
  style="
      background-image: url('https://mdbcdn.b-cdn.net/img/new/slides/041.jpg');
      height: 400px;
      background-repeat: no-repeat;
      background-size: cover;
      margin-top: -1rem !important;">

  <div class="mask w-100 d-flex flex-column" style="background-color: rgba(0, 0, 0, 0.6);">
    <div class="d-flex justify-content-center w-100 mt-auto">
      <!-- 该区块会自动对齐到底部 -->
      <div class="py-4 text-white">
        <h1 class="mb-3">欢迎来到工具中心!</h1>
        <a class="btn btn-outline-light btn-lg" href="{{site.url}}/puppies" role="button">查看我们的最新工具!</a>
      </div>
    </div>
  </div>
</div>

需求2:标题和CTA垂直居中对齐

如果需要居中展示,直接给mask层加弹性对齐类即可,修改后完整代码:

<div
  class="d-flex align-items-stretch mb-3 rounded shadow text-center bg-image img-fluid"
  style="
      background-image: url('https://mdbcdn.b-cdn.net/img/new/slides/041.jpg');
      height: 400px;
      background-repeat: no-repeat;
      background-size: cover;
      margin-top: -1rem !important;">

  <div class="mask w-100 d-flex align-items-center justify-content-center" style="background-color: rgba(0, 0, 0, 0.6);">
    <div class="py-4 text-white">
      <h1 class="mb-3">欢迎来到工具中心!</h1>
      <a class="btn btn-outline-light btn-lg" href="{{site.url}}/puppies" role="button">查看我们的最新工具!</a>
    </div>
  </div>
</div>

内容的提问来源于stack exchange,提问作者ShrockCo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:57:03