在 Bootstrap 中垂直居中 div 5

Center div vertically in Bootstrap 5

如何让 div 在 bootstrap 5 中垂直居中? 它应该在 div 和屏幕结束之前的内容中间对齐。

试过这个:

    <div>some content</div>
    <div class="d-flex flex-column min-vh-100 justify-content-center align-items-center">
        <div>div that should be centered</div>
    </div>

它使页面比实际更长。 div 看起来不居中。

你可以这样做:

  • 用屏幕宽度和高度为 100% 的 div 包裹所有内容。
  • 第二个 div 使用 flex-grow-1,因此它占用剩余的高度并将所有内容居中。

<!doctype html>
<html lang="en">
  <head>
    <!-- Bootstrap core CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  </head>
  <body>
    <div class="d-flex flex-column min-vh-100 min-vw-100">
      <div>This div is not centered.</div>
      <div class="d-flex flex-grow-1 justify-content-center align-items-center">
        <div>This div is centered.</div>
      </div>
    </div>
  </body>
</html>