gpt4 book ai didi

css - 带 flexbox 的垂直居中 div

转载 作者:行者123 更新时间:2023-11-28 11:05:51 26 4
gpt4 key购买 nike

我尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com