我有一个流畅的布局,由页眉、正文和页脚组成,所有这些都应该始终可见。
问题 如果一个元素被应用在 flex 布局之外,那么该元素将被外部元素的高度推到视口(viewport)之外。我如何维护一个与外部元素尺寸无关的始终在 View 中的布局,以便元素始终可见?
.main {
height: 100vh;
text-align: center;
}
.external-element-no-control {
height: 70px; // could be any height
background: black;
}
.content-wrapper {
position: relative;
height: 100%;
}
.content {
height: 100%;
display: flex;
flex-direction: column;
}
.blocks {
flex: 1;
}
.one {
background: cyan;
flex: 0;
}
.two {
background: lightGreen;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
.three {
background: pink;
}
<div class="main">
<div class="external-element-no-control"></div>
<div class="content-wrapper">
<div class="content">
<div class="block one">
<div>
<h1>This is my title </h1>
<p>With some sub text</p>
</div>
</div>
<div class="block two">
<div>This is my main content</div>
</div>
<div class="block three">
<div>This is my call to action</div>
</div>
</div>
</div>
</div>
最佳答案
在父元素上使用另一个 flex 容器。这将使您的子元素无需定义高度即可消耗剩余空间。
给 body
元素 display: flex
和 flex-direction: column
。
给外部元素 height: auto
,所以它会调整到内容高度。
给主要内容 flex: 1
,所以它会占用所有剩余空间。
.main {
height: 100vh;
text-align: center;
display: flex;
flex-direction: column;
}
.external-element-no-control {
color: white;
background: black;
min-height: 0;
}
.content-wrapper {
flex: 1;
display: flex;
}
.content {
flex: 1;
display: flex;
flex-direction: column;
}
.blocks {
flex: 1;
}
.one {
background: cyan;
flex: 0;
}
.two {
background: lightGreen;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
.three {
background: pink;
}
body {
margin: 0;
}
<div class="main">
<div class="external-element-no-control">could<br>be<br>any<br>height</div>
<div class="content-wrapper">
<div class="content">
<div class="block one">
<div>
<h1>This is my title </h1>
<p>With some sub text</p>
</div>
</div>
<div class="block two">
<div>This is my main content</div>
</div>
<div class="block three">
<div>This is my call to action</div>
</div>
</div>
</div>
</div>
关于css - 防止 flex 容器溢出视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364648/