所以我有一个高度为 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>
我做错了什么?
最佳答案
简单的绝对定位。
.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
.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/