Html Flexbox 垂直填充可用空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40020921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:55:05  来源:igfitidea点击:

Flexbox fill available space vertically

htmlcssflexbox

提问by Jim-Y

Now in a flexboxrow I can write

现在flexbox我可以连续写

<div layout="row">
  <div>some content</div>
  <div flex></div> <!-- fills/grows available space -->
  <div>another content</div>
</div>

I would like to achieve the same but vertically, like on this picture enter image description hereCurrently the problem is that the divwhich would need to grow doesn't have any heightso the two contents are below each other. I want my second content to be at the bottom of the parent container which has a fixed height!

我想实现相同但垂直的,就像这张图片 在此处输入图片说明目前的问题是需要增长的div没有任何高度,因此两个内容彼此低于。我希望我的第二个内容位于具有固定高度的父容器的底部!

I know I could solve this by positioning the second content absolute and bottom: 0;but can I achieve this with flexbox?

我知道我可以通过定位第二个内容绝对来解决这个问题,bottom: 0;但是我可以用flexbox?

回答by kukkuz

So you can try this:

所以你可以试试这个:

  1. flex-direction: columnfor the flex container.

  2. flex: 1for the element that needs to fill the remaining space.

  1. flex-direction: column对于 flex 容器。

  2. flex: 1对于需要填充剩余空间的元素。

See demo below where the flexboxspans the viewport height:

请参阅下面的演示,其中flexbox跨越视口高度:

body {
  margin: 0;
}
*{
  box-sizing: border-box;
}
.row {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.flex {
  flex: 1;
}
.row, .row > * {
  border: 1px solid;
}
<div class="row">
  <div>some content</div>
  <div class="flex">This fills the available space</div>
  <!-- fills/grows available space -->
  <div>another content</div>
</div>

Cheers!

干杯!

回答by Nenad Vracar

You just need to use flex-direction: columnon parent and flex: 1on middle div.

您只需要flex-direction: column在父级和flex: 1中间 div 上使用。

body,
html {
  padding: 0;
  margin: 0;
}
.row {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
.row > div:not(.flex) {
  background: #676EE0;
}
.flex {
  flex: 1;
  background: #67E079;
}
<div class="row">
  <div>some content</div>
  <div class="flex"></div>
  <!-- fills/grows available space -->
  <div>another content</div>
</div>