这几天使用flex开发大屏,遇到一个印象比较深的问题就是flex的子元素,在其他兄弟元素的高度不定的情况下,如何占满父元素的剩余空间?
效果图:
要点就是:
1、父元素要设置 display: flex;
2、父元素的主轴方向设置为从上到下 flex-direction: column;
3、父元素的高度能确定,不管是定高(height: 500px;),还是 100% 其父元素的高度
4、需要占满剩余高度的子元素,设置 flex:1; 或者 flex-grow:1;
因为 ( flex:1; ) == ( flex: 1 1 0%; ) == ( flex-grow:1;flex-shrink:1; flex-basis:0%;) == (父控件有剩余空间占1份放大,父控件空间不足按1缩小,自身的空间大小是0%)
如果你对另外两个属性要要求可以另外设置。
下面是测试的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.father{
color: #000;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
height: 500px;
width: 300px;
}
.child1{
background:red;
}
.child2{
background: green;
flex:1;
}
</style>
</head>
<body>
<div class="father">
<div class="child1">我的高度不定</div>
<div class="child2">我要占满father的剩余高度</div>
</div>
</body>
</html>
当然了,其实联想一下,就会发现,上面的方法应对 占满剩余宽度也是可行的,这个就看各位看官如何变通了,我就不再赘述了。
-----------------------------------------------------------------------分割线-------------------------------------------------------------
接下说说在flex:1 的子元素 overflow:hidden 失效的问题,这个问题 出现在当 flex父元素高度不足时,会被子元素撑开高度,这不是我们想要的,解决方法:
min-width: 0 或者 min-height: 0
width: 0 或者 height: 0
上面的方法都是可行的。