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

如何在Bootstrap 3的Flex行嵌套列中居中div元素?

解决Bootstrap 3中Flex列内元素的水平垂直居中问题

我来帮你搞定这个居中问题!你遇到的核心问题是Bootstrap 3的网格容器默认没有高度,且你的flex属性没补全水平居中的设置,调整一下CSS就能解决:

关键修改点

  • 给外层.row设置高度(比如占满视口高度min-height: 100vh,或者根据你的需求设固定高度),没有高度的话垂直居中根本无从谈起
  • 给.col-md-8添加display: flex,让它成为flex容器,这样内部的.centered-column才能继承有效的布局上下文
  • 给.centered-column补充align-items: center实现水平居中,同时保留justify-content: center实现垂直居中

修改后的完整代码

CSS部分

span { 
  font-size: 20px; 
} 

/* 给row设置高度,确保垂直居中有空间 */
.row { 
  display: -webkit-flex; 
  display: -ms-flexbox; 
  min-height: 100vh; /* 占满整个视口高度,可根据需求调整 */
} 

.col-md-8 { 
  background-color: lightblue; 
  display: flex; /* 让col成为flex容器 */
} 

.centered-column { 
  display: flex; 
  flex-direction: column; 
  justify-content: center; /* 垂直居中 */
  align-items: center; /* 水平居中 */
  width: 100%; /* 确保占满父容器宽度,避免内容收缩 */
}

HTML部分

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
  <div class="row">
    <div class="col-md-4 text-center">
      <div class="row">
        <div class="col-md-12">
          <span>Row number 1</span>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <span>Row number 2</span>
        </div>
      </div>
    </div>
    <div class="col-md-8">
      <div class="centered-column">
        <span>Some text</span> <!-- 顺便修复了你未闭合的span标签 -->
      </div>
    </div>
  </div>
</div>

为什么之前的方法没生效?

你参考的居中指南是通用方案,但Bootstrap 3的.col-md-8默认是块级元素,没有设置display: flex,而且外层.row没有高度,导致justify-content: center没有垂直方向的空间可以发挥作用。补充这些属性后,flex的居中逻辑就能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:25:15