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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39697530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:50:45  来源:igfitidea点击:

How to vertically align div on page with flexbox

htmlcssflexbox

提问by EricC

The following is not vertically aligning the div with text in browser tab (it is horizontally aligning correctly):

以下不是将 div 与浏览器选项卡中的文本垂直对齐(它正确地水平对齐):

<div style="height: 100%; display: flex; align-items: center; justify-content: center;">

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

</div>

What is wrong?

怎么了?

回答by Syam Pillai

The problem is with the height you given to the parent container. The height :100%does not take whole height. change that to 100vhor like that

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

Here is the updated Demo

这是更新的演示

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

回答by Santosh Khalse

Please try bellow following code

请尝试以下代码

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;
}
<div class="demo-wp">

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

</div>

回答by Alec von Barnekow

Try this:

尝试这个:

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

It's because your parent divdoesn't take the full height.

那是因为你的父母div没有完全身高。

回答by Rohit Yadav

try this

尝试这个

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