可以比 body 大的居中 div
Centering div that can be bigger than body
我正在处理一个包含 login/register 页面的项目。它基本上是白色的 div body 应该垂直和水平居中,但有时可以比 body 大。
当 div 很小的时候一切都很好,但是当它比 body 大时,我只希望它在顶部和底部有小的填充。
我怎样才能做到这一点?我一整天都在寻找答案,终于到了这里。帮助我的人 :C
#wrap {
height: 300px;
width: 150px;
display: flex;
justify-content: center;
align-items: center;
background: #DDD;
}
#content {
background: #000;
width: 100px;
height: 400px;
}
<div id="wrap">
<div id="content">
</div>
</div>
使用min-height
代替height
,并在顶部和底部添加padding
。使用box-sizing: border-box
防止padding改变高度:
.wrap {
box-sizing: border-box;
min-height: 300px;
width: 150px;
padding: 20px;
display: flex;
justify-content: center;
align-items: center;
background: #DDD;
}
.content {
background: #000;
width: 100px;
height: 400px;
}
/** for the demo **/
.content--small {
height: 100px;
}
body {
display: flex;
justify-content: space-around;
align-items: flex-start;
}
<div class="wrap">
<div class="content">
</div>
</div>
<!-- for the demo -->
<div class="wrap">
<div class="content content--small">
</div>
</div>
您可以使用 min-height
而不是 height
并在包装上使用小的顶部和底部填充,如下所示。当内部元素高于包装器时,它将扩展包装器并额外保留填充。
#wrap {
min-height: 300px;
padding: 10px 0;
width: 150px;
display: flex;
justify-content: center;
align-items: center;
background: #DDD;
}
#content {
background: #000;
width: 100px;
height: 400px;
}
<div id="wrap">
<div id="content">
</div>
</div>
我正在处理一个包含 login/register 页面的项目。它基本上是白色的 div body 应该垂直和水平居中,但有时可以比 body 大。
当 div 很小的时候一切都很好,但是当它比 body 大时,我只希望它在顶部和底部有小的填充。
我怎样才能做到这一点?我一整天都在寻找答案,终于到了这里。帮助我的人 :C
#wrap {
height: 300px;
width: 150px;
display: flex;
justify-content: center;
align-items: center;
background: #DDD;
}
#content {
background: #000;
width: 100px;
height: 400px;
}
<div id="wrap">
<div id="content">
</div>
</div>
使用min-height
代替height
,并在顶部和底部添加padding
。使用box-sizing: border-box
防止padding改变高度:
.wrap {
box-sizing: border-box;
min-height: 300px;
width: 150px;
padding: 20px;
display: flex;
justify-content: center;
align-items: center;
background: #DDD;
}
.content {
background: #000;
width: 100px;
height: 400px;
}
/** for the demo **/
.content--small {
height: 100px;
}
body {
display: flex;
justify-content: space-around;
align-items: flex-start;
}
<div class="wrap">
<div class="content">
</div>
</div>
<!-- for the demo -->
<div class="wrap">
<div class="content content--small">
</div>
</div>
您可以使用 min-height
而不是 height
并在包装上使用小的顶部和底部填充,如下所示。当内部元素高于包装器时,它将扩展包装器并额外保留填充。
#wrap {
min-height: 300px;
padding: 10px 0;
width: 150px;
display: flex;
justify-content: center;
align-items: center;
background: #DDD;
}
#content {
background: #000;
width: 100px;
height: 400px;
}
<div id="wrap">
<div id="content">
</div>
</div>