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

如何在Bootstrap 5.3的section中实现内容居中?

问题描述

我希望让每个高度为100vh的section内的内容在页面中垂直及水平居中,当前使用Bootstrap v5.3.0-alpha1,现有代码如下,参考图片如下,请问该如何实现?

内容垂直水平居中效果

现有代码

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 class="content" 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">
                    <img src="https://via.placeholder.com/350/09f/fff.png" />
                </div>
            </div>
        </div>
    </section>

    <section class="content" style="background-color: moccasin;">
        <div class="container">
            <div class="row">
                <div class="col-lg-6">
                    <h1>heading</h1>
                    <p>test</p>
                </div>

                <div class="col-lg-6">
                    <img src="https://via.placeholder.com/350/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:使用Bootstrap内置Flex类(推荐)

直接给每个section.content添加三个Bootstrap内置类,利用框架样式快速完成居中:

  • d-flex:将section设为flex容器
  • align-items-center:让内部元素垂直居中
  • justify-content-center:让内部元素水平居中

修改后的section示例:

<section class="content d-flex align-items-center justify-content-center" style="background-color: lightgreen;">

所有section都添加这三个类后,内部的container就能在100vh的section中实现垂直水平居中。

方式2:自定义CSS实现

如果不想修改HTML结构,直接修改.content的CSS样式,添加flex相关属性:

.content {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

此方法同样能达到内容垂直水平居中的效果,和方式1表现一致。


内容的提问来源于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 19:20:47