如何以最小高度将div中的H1标题垂直居中

时间:2019-05-09 05:50:17

标签: twitter-bootstrap bootstrap-4

我在此div上带有背景图片,并对其应用了最小高度(400像素)属性。我希望标题h1出现在其垂直中心的正上方。

我使用了提供的my-auto类,但是它什么也没做。甚至与h-100班级一起尝试过。

Codepen:https://codepen.io/anon/pen/QRywbw

<section id="message">
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-8 my-auto">
<h1 class="text-right align-middle">Give <span>alternate medicine</span> a chance!</h1>
</div>
</div>
</div>
</section>

#message {
min-height: 400px;
background: url(https://via.placeholder.com/1000x400) no-repeat;
background-size: cover;
}

我希望文本垂直居中。

4 个答案:

答案 0 :(得分:0)

<section id="message" class="d-flex align-items-center">

答案 1 :(得分:0)

使用flexbox垂直居中可能会有更多惯用的自举方法,但这是使用flexbox的普通CSS中的一种方法:

#message {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  background: url(https://via.placeholder.com/1000x400) no-repeat;
  background-size: cover;
}

#message h1 {
  color: #fff;
}

我经常将此作为关于https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/的好文章。

答案 2 :(得分:0)

使任何东西垂​​直居中的最佳方法是使用flex-box。

#message{
  min-height: 400px;
  background: url(https://via.placeholder.com/1000x400) no-repeat;
  background-size: cover;
  display:flex;
  flex-direction:column;
  justify-content:center;
}

答案 3 :(得分:0)

您可以使用此CSS,并且可以看到h1标签垂直居中。

#message{
        min-height: 400px;
        background: url(https://via.placeholder.com/1000x400) no-repeat;
        background-size: cover;
        position: relative;
    }

#message h1 {
    color: #fff;
    position: absolute;
    top: 47%;
    text-align: center;
    width: 100%;
    margin: 0 auto;
}

谢谢