如何使用flexbox将页面上的div垂直对齐

时间:2016-09-26 08:00:51

标签: html css css3 flexbox

以下内容并非垂直对齐浏览器标签中的文本(水平对齐正确):



<a href="#" onclick="window.open(document.referrer); return false;">back</a>
&#13;
&#13;
&#13;

有什么问题?

4 个答案:

答案 0 :(得分:23)

问题在于您给父容器的高度。 height :100%不占整个高度。将其更改为100vh或类似

以下是更新的 Demo

&#13;
&#13;
.container{
  height: 100vh; 
  display: flex; 
  align-items: center; 
  justify-content: center;
}
&#13;
<div class="container">
  <div>
    Some vertical and horizontal aligned text
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

请尝试以下代码

&#13;
&#13;
body, html{
  height:100%;
  width:100%;
  padding:0px;
  margin:0px;
}

.demo-wp{
  height: 100%; 
  display: flex; 
  align-items: center; 
  justify-content: center;
  background:green;
  height:100%;
}

.inner-div{
  background:gold;
  padding:20px;
}
&#13;
<div class="demo-wp">

  <div class="inner-div">
    Some vertical and horizontal aligned text
  </div>

</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

试试这个:

&#13;
&#13;
<div style="height: 100vh; display: flex; align-items: center; justify-content: center;">
  <div>
    Some vertical and horizontal aligned text
  </div>
</div>
&#13;
&#13;
&#13;

这是因为您的父母div没有达到最高。

答案 3 :(得分:-1)

试试这个

&#13;
&#13;
<div style="height: 100%; display: -webkit-flex; display: flex; align-items: center; justify-content: center; background-color: lightgrey;">

  <div>
    Some vertical and horizontal aligned text
  </div>

</div>
&#13;
&#13;
&#13;