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

如何在Bootstrap5网格布局中实现文本垂直居中对齐

解决方案

你使用的是Bootstrap 5版本,框架本身内置了flex布局相关的工具类,无需额外编写自定义CSS,两种常用方案可选:

方案1:整行所有列统一垂直居中(推荐)

Bootstrap的.row默认采用flex布局,只需给设置了自定义高度的.row添加align-items-center类,即可让该行内所有列的内容自动垂直居中。
修改后的完整代码如下:

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <!-- 引入Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container-fluid bg-dark text-white">
        <!-- 给row添加align-items-center类实现垂直居中 -->
        <div class="row align-items-center" style="height:100px;">
            <div class="col-sm-4 bg-primary">R1 C1需要垂直居中对齐</div>
            <div class="col-sm-6 bg-danger">R1 C2需要垂直居中对齐</div>
            <div class="col-sm-2 bg-info">R1 C3需要垂直居中对齐</div>
        </div>
        <!-- 第二个自定义高度的row同理添加类 -->
        <div class="row align-items-center" style="height:79px">
            <div class="col-sm-6 bg-info">R2 C1需要垂直居中对齐</div>
            <div class="col-sm-6 bg-danger">R2 C2需要垂直居中对齐</div>
        </div>
    </div>
</body>
</html>

方案2:单独控制指定列垂直居中

如果不需要整行所有列都居中,只需给需要居中的对应列添加d-flex和align-items-center两个类,将列本身设置为flex容器即可让内部内容垂直居中,示例代码片段:

<div class="row" style="height:100px;">
    <!-- 仅给需要居中的列添加类 -->
    <div class="col-sm-4 bg-primary d-flex align-items-center">R1 C1需要垂直居中对齐</div>
    <div class="col-sm-6 bg-danger">R1 C2不需要居中</div>
    <div class="col-sm-2 bg-info">R1 C3不需要居中</div>
</div>

内容的提问来源于stack exchange,提问作者Hưng Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:54:02