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;
}
 <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>

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

在此处输入图像描述

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

原文由 fightstarr20 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 459
1 个回答

在这种情况下 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;
}

更改后的屏幕截图。

原文由 Aamir Khan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题