Bootstrap:如何在容器中垂直居中对齐

时间:2019-07-13 19:13:57

标签: bootstrap-4 containers centering

我今天在这里寻求帮助,因为我试图将div在我的网页上垂直居中(我正在使用Bootstrap)。

我首先做到了这一点:

<div class="row h-100">
  <div class="col-md-3 my-auto">
    <img src="public/img/1.jpg" class="img-circle img-no-padding img-responsive" alt="Rounded Image" width=200 height=200>
  </div>
  <div class="col-md-9 my-auto">
    <h1 class="merriweather text-white mb-3">Title</h1>
    <p class="merriweather text-white">Again and again, we've seen him make tough choices when easier ones were available.</p>
    </div>
  </div>
</div>

但是然后在我的代码中,我必须添加一个div class =“ container”:

<div class="container">
  <div class="row h-100">
    <div class="col-md-3 my-auto">
      <img src="public/img/1.jpg" class="img-circle img-no-padding img-responsive" alt="Rounded Image" width=200 height=200>
    </div>
    <div class="col-md-9 my-auto">
      <h1 class="merriweather text-white mb-3">Titre</h1>
      <p class="merriweather text-white">Again and again, we've seen him make tough choices when easier ones were available.</p>
    </div>
  </div>
</div>

当我这样做时,我不知道为什么,但是它不再起作用了。我尝试了其他类似使用“ align-self-center”类的方法,但是没有任何效果。

您能帮我弄清楚为什么我的“容器”类在我的代码上不起作用吗?如何使它垂直居中?

谢谢

1 个答案:

答案 0 :(得分:0)

无论哪种方式,都可以通过使用CSSposition属性来使用transform。请确保将parent元素设置为relative

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}
<div class="container">
  <div class="row h-100 center">
    <div class="col-md-3 my-auto ">
      <img src="public/img/1.jpg" class="img-circle img-no-padding img-responsive" alt="Rounded Image" width=200 height=200>
    </div>
    <div class="col-md-9 my-auto">
      <h1 class="merriweather text-white mb-3">Titre</h1>
      <p class="merriweather text-white">Again and again, we've seen him make tough choices when easier ones were available.</p>
    </div>
  </div>
</div>