gpt4 book ai didi

html - 使用视口(viewport)高度在父级内部垂直居中 div

转载 作者:太空宇宙 更新时间:2023-11-03 23:14:37 25 4
gpt4 key购买 nike

所以我有一个高度为 100vh - 55px 的 div,并且我有一个 div,无论如何我都希望在父级内部垂直居中。我将如何继续这样做?这就是我现在拥有的:

/* home.css | By Seb R | Ekchö */

.lander {
height: calc(100vh - 55px);
background: blue;
overflow: hidden;
}
.lander .content {
height: 300px;
margin-top 30vh;
background: red;
}
<div class="lander">
<div class="content"></div>
</div>

我做错了什么?

最佳答案

简单的绝对定位。

JSfiddle Demo

.lander {

height: calc(100vh - 55px);
background: blue;
overflow: hidden;
position: relative;

}

.lander .content {

height: 300px;
background: red;
position: absolute;
width: 100%;
left: 0;
top: 50%;
margin-top: -150px; /* half height */

}
<div class="lander">
<div class="content"></div>
</div>

Flexbox

JSfiddle Demo

.lander {
height: calc(100vh - 55px);
background: blue;
display:flex;
flex-direction:column;
justify-content:center;
}
.lander .content {
height: 300px;
background: red;
}
<div class="lander">
<div class="content"></div>
</div>

显然在某些时候 300px 可能比您分配的视口(viewport)更大(如 SO 片段中所示),因此您可能需要在此之前进行调整。

关于html - 使用视口(viewport)高度在父级内部垂直居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31116762/

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