如何让flex
孩子不与顶部填充重叠?
在此示例中,子.large
居中,但由于其较大的高度,其顶部位于其父级的顶部边界上方。有没有办法防止这种情况,并使.large
在没有JS的.flex
填充顶部之后? flex-start
将是不好的解决方案,因为.flex
内的块可能具有较小的高度,并且必须位于.flex
的中心。 .flex
必须定位为absolute
或fixed
。
https://jsfiddle.net/zoxamy9f/1/
.large {
background: red;
height: 200%;
flex: 1;
}
html, body {
height: 100%;
overflow: hidden;
}
.flex {
position: absolute;
left: 0;
top: 0;
width: 100%;
padding-top: 10%;
height: 100%;
background: black;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
}

<div class="flex">
<div class="large"></div>
</div>
&#13;
答案 0 :(得分:1)
你是否有可能将你的结构改变成这样的东西?
.large {
background: red;
height: 200%;
flex: 1;
}
html,
body {
height: 100%;
overflow: hidden;
}
.wrap {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: black;
}
.flex {
width: 100%;
height: 100%;
margin-top: 10%;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
<div class="wrap">
<div class="flex">
<div class="large"></div>
</div>
</div>
答案 1 :(得分:1)
如果您在flex
和large
之间添加包装,则可以完成
我还使用了视口单元vh
而不是%
,因为百分比无法启用垂直居中。
Stack snippet - 内容很多
.wrapper {
display: inline-flex;
flex-direction: column;
width: 100%;
height: calc(100% - 10vh);
justify-content: center;
}
.large {
background: red;
width: 100%;
}
.flex {
position: absolute;
left: 0;
top: 0;
width: 100%;
padding-top: 10vh;
height: 100%;
background: black;
overflow: auto;
box-sizing: border-box;
}
<div class="flex">
<div class="wrapper">
<div class="large">
Content 1
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
<br> Content
</div>
</div>
</div>
Stack snippet - 内容很少
.wrapper {
display: inline-flex;
flex-direction: column;
width: 100%;
height: calc(100% - 10vh);
justify-content: center;
}
.large {
background: red;
width: 100%;
}
.flex {
position: absolute;
left: 0;
top: 0;
width: 100%;
padding-top: 10vh;
height: 100%;
background: black;
overflow: auto;
box-sizing: border-box;
}
<div class="flex">
<div class="wrapper">
<div class="large">
Content 1
<br> Content
<br> Content
<br> Content
</div>
</div>
</div>