首页 > 解决方案 > Flexbox - Fill remaining space

问题描述

I have a basic flexbox layout like this..

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>

I am trying to make the top div fill the remaining space, the bottom div is dynamic so the height changes depending on the text. My result looks like this..

enter image description here

Is flexbox the best thing to use in this situation?

标签: htmlcssflexbox

解决方案


在这种情况下使用 flexbox 是不是最好的选择?

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

据我了解,要达到您想要的结果,您需要设置height: 100%on#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;
}

修改后的截图。


推荐阅读