如何使flex元素完全展开以填充包含的元素?

Ant*_*ong 3 html css css3 flexbox

这是我的代码。

我希望元素.container充分扩展并占据的面积.toplevel

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
}

.container {
  display: flex;
  border: solid 1px red;
  height: 100%;
  flex: 0 1 auto;
  flex-direction: column;
  // min-height: 800px;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="up">
      This is down
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

但是,似乎要使.container高度更大,唯一的方法是定义一个min-height。太不灵活了,因为我将为不同的设备尺寸提供不同的值。

我该如何解决?

LGS*_*Son 5

Simpy添加display: flex.toplevelheight: 100%从中删除.container

这项工作基于以下事实:可以使用align-items属性控制弹性行项目的高度行为。由于默认情况下具有stretch,它将填充其父级高度。

需要注意的是,一般而言,谈到Flexbox时,最好使用其自己的属性而不是height/ width。这样,您还可以获得更好的跨浏览器支持。

堆栈片段

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
  display: flex;              /* added  */
}

.container {
  display: flex;
  border: solid 1px red;
  /*height: 100%;                removed  */
  flex: 1 1 auto;            /*  changed, flex row item need the grow value
                                          to be 1 to fill its parent's width  */
  flex-direction: column;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="down">
      This is down
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)