
本文详解在 bootstrap 5.3+ 中实现 section 内容(文字、图片等)在视口内**垂直+水平居中**的多种可靠方法,涵盖 flex 工具类、容器嵌套逻辑及常见误区修正。
在 Bootstrap 5 中,要将
✅ 正确做法:使用 d-flex + justify-content-center + align-items-center
最推荐、最简洁的方式是将 .content(即 section)本身设为 Flex 容器,并应用居中类:
Heading
Centered both horizontally and vertically
@@##@@
? 关键点说明:d-flex:将 变为 Flex 容器(必需);justify-content-center:实现水平居中;align-items-center:实现垂直居中;min-height: 100vh(推荐替代 height: 100vh):确保 section 至少占满视口高度,避免内容塌陷;
⚠️ 原代码问题分析
你原结构中存在几个典型误区:
- ❌ 在 .row 上误用 justify-center(Bootstrap 5 中无此 class,正确为 justify-content-center);
- ❌ 混用 text-center(仅影响内联文本对齐)和 mx-auto(仅水平居中块级元素,但无法垂直居中);
- ❌ .row 默认是 flex-direction: row,其 align-items 默认为 stretch,不会自动垂直居中子列;
- ❌ col-lg-10 mx-auto col-lg-5 写法错误(重复 col-lg-* 类,后者会覆盖前者)。
✅ 进阶方案:保留栅格结构 + 居中控制
若需严格保持两栏布局(如左文右图),仍可居中整行内容:
Heading
Left-aligned on large screens, centered on mobile
@@##@@
? 提示:
- 外层 d-flex align-items-center 确保整行在视口中垂直居中;
- row.justify-content-center 让两列整体水平居中;
- 右侧列内嵌 d-flex justify-content-center 精确控制图片水平位置;
- 使用 img-fluid 保证响应式缩放。
? 注意事项总结
- ✅ 始终优先使用 min-height: 100vh 而非 height: 100vh,避免内容溢出时布局异常;
- ✅ 不要依赖 text-center 实现块级元素居中——它只作用于内联内容(如文字、);
- ✅ Bootstrap 5 已移除旧版 center-block 和 text-xs-center 等,统一使用 text-{breakpoint}-{align} 和 justify-content-* / align-items-*;
- ✅ 若需兼容 Safari 旧版本,可添加 -webkit-box-align: center 等前缀(现代项目通常无需);
- ✅ 自定义 CSS 中慎用 position: absolute 居中(破坏响应式与可访问性),Flex 方案更健壮。
掌握这些 Flex 工具类组合,你就能在任意 Bootstrap 5 项目中,精准、语义化、响应式地实现内容居中——无需额外 JS,也无需 hack 式 margin 调整。










