防止Flex容器溢出视口

时间:2019-08-05 19:01:01

标签: css flexbox

我有一个流畅的布局,包括页眉,正文和页脚,所有这些都应该始终在视野中。

问题 如果将元素应用到flex布局之外,则将元素按外部元素的高度推到视口之外。如何保持始终在视图中布局,而该布局与外部元素尺寸无关,因此元素始终可见?

.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>

1 个答案:

答案 0 :(得分:1)

在父元素上使用另一个flex容器。这将使您的子元素无需定义高度即可占用剩余空间。

给出body元素display: flexflex-direction: column

提供外部元素height: auto,以便将其调整为内容高度。

提供主要内容flex: 1,因此它会占用所有剩余空间。

jsFiddle demo

.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>