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

如何垂直居中Bootstrap卡片?已实现水平居中但垂直居中失败

解决Bootstrap卡片垂直居中问题

问题出在你的布局容器没有占据整个视口高度,mt-*类只是添加固定的顶部外边距,没法让卡片真正垂直居中。要实现卡片在屏幕中央(水平+垂直),可以用Bootstrap的Flex布局工具类,具体修改如下:

  1. 给<html>和<body>添加h-100类,让它们占据整个视口高度
  2. 把原来的container+row结构替换成Flex容器类,直接让卡片在容器内垂直水平居中

修改后的完整代码:

<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><%= title %></title>
  <link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
    crossorigin="anonymous"
  />
</head>
<body class="h-100 d-flex align-items-center justify-content-center">
  <div class="col-3">
    <div class="card">
      <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">
          Some quick example text to build on the card title and make up the
          bulk of the card's content.
        </p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
      </div>
    </div>
  </div>

  <script
    src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
    crossorigin="anonymous"
  ></script>
</body>
</html>

关键类作用说明:

  • h-100:让元素高度占满父容器的100%,确保html和body撑满整个屏幕高度
  • d-flex:将body设置为Flex容器,启用Flex布局
  • align-items-center:让Flex容器内的元素在垂直方向上居中
  • justify-content-center:让Flex容器内的元素在水平方向上居中
  • col-3:保持卡片宽度为屏幕的1/4,和你原本的宽度设置一致

这样修改后,卡片就会完全居中在屏幕中央了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:22:04