Flexbox - 填充剩余空间

fig*_*r20 4 html css flexbox

我有一个像这样的基本 flexbox 布局..

body,html {
  height:100%;
  width:100%;

}

#container {
  width:100%;
  background:grey;
  display:flex;
  flex-direction:column;
}

.top {
  background:red;
  flex:1;
  padding:20px;
}

.bottom {
  background:yellow;
  flex:1;
  padding:20px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
	<div class="top">
  Top Content
	</div>
	<div class="bottom">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut venenatis, arcu vitae sollicitudin pellentesque, quam libero imperdiet urna, eu rhoncus lorem dolor sed neque. Donec ex risus, pretium ut maximus fringilla, euismod id mi. Phasellus ligula sem, iaculis ut urna eget, efficitur vulputate sem.
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我试图让顶部 div 填充剩余空间,底部 div 是动态的,因此高度会根据文本而变化。我的结果看起来像这样..

在此处输入图片说明

在这种情况下,flexbox 是最好的选择吗?

Aam*_*han 8

在这种情况下,flexbox 是最好的选择吗?

是的,在这种情况下使用 flexbox 是个好主意。

为了达到您想要的结果,我明白了,你需要设置height: 100%#container,这样它占据所有可以利用的空间。然后设置flex-grow: 0.bottom,这样它不会增长。

所以你的 CSS 应该是:

#container {
  width:100%;
  height:100%;
  background:grey;
  display:flex;
  flex-direction:column;
}

.top {
  background:red;
  flex: 1 0 auto; // Grow, don't shrink
  padding:20px;
}

.bottom {
  background:yellow;
  flex: 0 0 auto; // don't grow, take up only needed space
  padding:20px;
}
Run Code Online (Sandbox Code Playgroud)

修改后截图。