小编典典

Bootstrap 4中心垂直和水平对齐

css

我有一个页面,其中仅存在表单,并且我希望将表单放置在屏幕的中央。

<div class="container">
  <div class="row justify-content-center align-items-center">
    <form>
      <div class="form-group">
        <label for="formGroupExampleInput">Example label</label>
        <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
      </div>
      <div class="form-group">
        <label for="formGroupExampleInput2">Another label</label>
        <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
      </div>
    </form>   
  </div>  
</div>

justify-content-center对齐表格水平,但我无法弄清楚如何垂直对齐。我已经尝试使用align-items- centeralign-self-center,但是它不起作用。

我想念什么?


阅读 1173

收藏
2020-05-16

共1个答案

小编典典

更新2019 - Bootstrap 4.3.1

没有必要 进行 额外的CSS 。Bootstrap中已经包含的内容将起作用。确保表格的容器为 全高 。Bootstrap4现在具有h-100100%高度的类…

垂直中心:

<div class="container h-100">
  <div class="row h-100 justify-content-center align-items-center">
    <form class="col-12">
      <div class="form-group">
        <label for="formGroupExampleInput">Example label</label>
        <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
      </div>
      <div class="form-group">
        <label for="formGroupExampleInput2">Another label</label>
        <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
      </div>
    </form>   
  </div>
</div>

物品居中放置的容器的高度应为100% (或相对于居中物品所需的高度)

注意:在任何元素上使用height:100%百分比高度 )时,该元素
将采用其容器的高度

。在现代浏览器height:100vh;中,可以使用vh单位%来获得所需的高度。

因此,您可以设置html,正文{height:100%},或min-vh-100在容器上使用新类,而不是h-100


水平中心:

  • text-centerdisplay:inline元素和列内容为中心
  • mx-auto 用于在flex元素内部居中
  • offset-*mx-auto可用于将 列居中.col-
  • justify-content-center中心柱col-*)的内部row
2020-05-16