css - 防止 flex 容器溢出视口(viewport)

标签 css flexbox

我有一个流畅的布局,由页眉、正文和页脚组成,所有这些都应该始终可见。

问题 如果一个元素被应用在 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: 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>

关于css - 防止 flex 容器溢出视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364648/

相关文章:

javascript - 单击时使用 jQuery 更改图像不起作用

html - 如何垂直居中对齐文本?

jquery - 如果为 :empty 则隐藏父 div

html - 当所有子项都有 flex 属性时,父项的 justify-content 是否重要?

javascript - 响应式正方形网格内的响应式正方形网格

html - 为什么我的导航栏顶部有一个空白区域?

animation - CSS3 动画 :element moved to its initial position after @keyframes actions

css - PrimeNG 日历 - 覆盖默认样式

angularjs - 基本 Angular Material 布局/flex 示例不起作用

css - 将类 "collapse"添加到 flex 网格会导致间距不均匀