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

如何在Bootstrap 5.3.0-alpha1中实现section内容居中?

解决Bootstrap 5.3中Section内容居中的问题

核心问题分析

  • 你的container和row用法整体正确,但第二个section的列标签存在重复类名冲突(col-lg-10和col-lg-5重复设置),这会导致布局异常。
  • 对齐样式的添加位置取决于你要实现的居中类型:
    • 水平居中:若要让行内所有列整体水平居中,给row添加justify-content-center类;若仅需单列水平居中,给目标列添加mx-auto类(块级元素居中)或text-center类(文本/行内元素居中)。
    • 垂直居中:由于你的section设置了100vh高度,要让容器内内容垂直居中,需给section添加Flex布局类d-flex align-items-center,同时保留高度设置。

修正后的完整代码

CSS 部分

.content {
    height: 100vh;
}

HTML 部分

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Test</title>

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
        <link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}" />
    </head>
    <body>
            <!-- 第一个section:内容水平+垂直居中,文本在大屏左对齐、小屏居中 -->
            <section class="content d-flex align-items-center" style="background-color: lightgreen;">
            <div class="container">
                <div class="row">
                    <div class="col-lg-6 text-center text-lg-start">
                        <h1>heading</h1>
                        <p>test</p>
                    </div>

                    <div class="col-lg-6 d-flex justify-content-center">
                        <img src="https://via.placeholder.com/200/09f/fff.png" />
                    </div>
                </div>
            </div>
        </section>

        <!-- 第二个section:单列水平居中,整体垂直居中 -->
        <section class="content d-flex align-items-center" style="background-color: moccasin;">
            <div class="container">
                <div class="row">
                    <div class="col-lg-5 mx-auto">
                        <h1>heading</h1>
                        <p>test</p>
                    </div>

                    <div class="col-lg-6 d-flex justify-content-center">
                        <img src="https://via.placeholder.com/200/09f/fff.png" />
                    </div>
                </div>
            </div>
        </section>
                <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    </body>
</html>

关键修改说明

  1. 给两个section都添加了d-flex align-items-center类,实现内容垂直居中。
  2. 修正了第二个section中列的重复类名问题,保留col-lg-5 mx-auto实现单列水平居中。
  3. 给图片所在列添加d-flex justify-content-center,确保图片在列内水平居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:31:57