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
How to vertically align div on page with flexbox
提问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 100vh
or 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 div
doesn'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>