我尝试使用 flexbox 将 div 垂直居中:
奇怪的是 align-items: center
没有改变任何东西。玩了一段时间后,我意识到我需要将 body 和 html 设置为 height:100%;
。
HTML:
<div id="login_container">
<div class="login"></div>
<div class="login"></div>
<div class="login"></div>
</div>
CSS:
#login_container {
display: flex;
align-items: center;
justify-content: center;
height:100%;
}
.login {
background-color: #008000;
width: 100px;
height: 100px;
margin: 2px;
}
为了比较:This fiddle正在工作 this one不是。
为什么要加
body,html {
height:100%;
}
让div垂直对齐?我错过了什么吗?
最佳答案
height
的默认值为auto
,这意味着您的html
/body
不会全屏显示。
要获得全屏内容,您必须将高度指定为 100%
或 100vh
。
so that the div is vertically aligned? Am I missing something?
是的,您的内容垂直居中于父级(在本例中垂直居中于 html
/body
的内容)。您刚刚错过了将 html
/body
的高度设置为 100%
(全屏)。
关于css - 带 flexbox 的垂直居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35535710/