如何在Bootstrap 4中垂直居中div?

Ale*_*ein 0 css bootstrap-4

我开始使用Bootstrap 4,并尝试创建一些基本布局。根据bootstrap 4 docs,我可以通过将class元素应用于align-items-center它们来垂直对齐它们。

我尝试在Codepen上做一个基本示例,但div不在垂直居中。

我做错了什么?

Jon*_*lin 6

如果要垂直居中这些元素,请将html和body的高度和宽度设置为100%。将width&height设置为100%可使元素采用其父元素的高度。

接下来,相应地设置所有子元素。在bootstrap中,width: 100%is w-100height:100%is h-100。此外,引导程序使用12列布局,因此将您的类从更改col-md-4col-md-6

注意:您可以在代码中的HTML和body中添加w-100和h-100以获得相同的效果。

<style>
    html,body{
      width:100%;
      margin:0;
        height:100%;
    }
</style>

<div class="container w-100 h-100">
    <div class="row align-items-center h-100">
      <div class="col-md-6">
        <h1 class="alert alert-primary">Vertical</h1>
      </div>
      <div class="col-md-6">
        <h1 class="alert alert-success">Vertical</h1>
      </div>
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)