【问题标题】:How to center div vertically in Bootstrap 4? [duplicate]如何在 Bootstrap 4 中垂直居中 div? [复制]
【发布时间】:2018-06-21 04:23:48
【问题描述】:

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

我尝试在 codepen 上执行 basic example,但 div 没有垂直定位在中心。

我做错了什么?

【问题讨论】:

  • Bootstrap 使用 12 列布局系统尝试将 col-md-4 更改为 col-md-6(假设您需要 2 列)。
  • @JonathanChaplin 我将 col-md-4 更改为 col-md-6,但此更改仅影响水平位置,而我正在寻找将这 2 个 div 垂直居中对齐
  • 好的,您需要在几个元素上添加 w-100 和 h-100 以获得全高和全宽。我将在下面发布解决方案。

标签: css bootstrap-4


【解决方案1】:

如果您想垂直居中这些元素,请将 html 和 body 的高度和宽度设置为 100%。将宽度和高度设置为 100% 会使元素采用其父级的高度。

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

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

<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>

【讨论】:

    猜你喜欢
    • 2014-07-15
    • 1970-01-01
    • 2019-06-12
    • 2019-06-19
    • 2011-05-25
    • 2022-07-19
    • 2011-05-20
    • 2015-01-12
    相关资源
    最近更新 更多