You need to enable JavaScript to run this app. 使用Bootstrap栅格布局如何将右侧卡片与左侧内容垂直居中
优惠活动
大模型
产品
解决方案
定价
更多

使用Bootstrap栅格布局如何将右侧卡片与左侧内容垂直居中

Bootstrap栅格列垂直居中实现方案

Bootstrap 4的.row默认就是弹性布局容器,本身内置了完整的垂直对齐工具类,无需编写自定义CSS代码就能实现需求。

操作步骤

  • 定位到包裹col-lg-8、col-lg-4两个栅格列的外层.row容器
  • 根据需求选择对应的对齐类添加到row上:
    • 若需要全屏幕尺寸下两个列都垂直居中,添加 align-items-center
    • 若仅在lg及以上大屏保持垂直居中,小屏堆叠时按自然文档流排布,添加 align-items-lg-center
      该类的作用是让弹性容器下的所有子元素(即两个栅格列)在交叉轴(垂直方向)居中对齐,不会改动列内部的内容布局,正好匹配“col-lg-4中的卡片与相邻col-lg-8的整体内容垂直居中”的效果。

优化提示

当前代码中给col-lg-4内的卡片设置了固定width: 18rem,在部分屏幕宽度下容易出现卡片溢出列容器的问题,可以把这个宽度值改成width: 100%,让卡片自适应列宽,避免出现横向滚动条。

修改后的参考代码

<div class="container">
<!-- 追加align-items-lg-center类实现大屏下的垂直居中 -->
<div class="row align-items-lg-center">
  <div class="col-lg-8">
    <div style="border-radius:2px;padding:10px;background-color:#2120220e;word-wrap: break-word;text-align:center;width:100%;height:auto" id="description" >Testing</div>
      <div class="line"></div>
    <h3>Your Answer</h3>
    <div style="margin-bottom:100px">
      <div style="padding:10px" class="form-group">
        <textarea rows="10" placeholder="Description" class="form-control" id="upload-editor"></textarea>
      </div>
      <div class="form-group">
        <label class="control control--checkbox">I Agree With the terms and service <input type="checkbox" id="TOS" name="scales"></label>
        <button style="float:right" onclick="upload()" class="btn btn-primary mb-2">Request Code</button>
      </div>   
    </div>
  </div>
  <div class="col-lg-4">
    <!-- 将卡片固定宽度改为100%适配列宽 -->
    <div class="card" style="width: 100%;">
      <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <a href="#" class="card-link">Card link</a>
        <a href="#" class="card-link">Another link</a>
      </div>
    </div>
  </div>
</div>
</div>

注意:不要把垂直对齐类单独加在某一个栅格列上,那样只会实现单个列内部的内容对齐,无法实现两个列基于整体高度的双向垂直居中效果。正确的对齐对象是作为弹性容器的外层 .row 元素。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 19:45:07