与flexbox共享相同的项目高度

时间:2015-01-30 21:32:00

标签: html5 css3 flexbox

我的笔:http://codepen.io/anon/pen/QwMRNL

如何让这3个div共享相同的行高并始终占据屏幕的整个高度?

即使只有3个或2个或1个项目。他们必须始终分享大小。

- 3 items means each item gets 33% height
- 2 items means each item gets 50% height
- 1 item means each item gets 100% height


<div id="flex">
  <div>Temperature</div>
  <div>Freeze</div>
  <div>Consumption</div>
</div>

#flex {
display: flex;
max-height: 100%;
align-content: center;
flex-direction: column;    
}


body {
margin:0;
padding:0;
}

#flex > div:nth-child(1){
background:blue;
}

#flex > div:nth-child(2){
background:red;
}

#flex > div:nth-child(3){
background:yellow;
}

更新:

请不要改变身高:身体100%,html标签!

2 个答案:

答案 0 :(得分:1)

在容器上使用justify-content:stretch;,在项目上使用flex-grow:1;

&#13;
&#13;
.container{
  display:flex;
  flex-direction:column;
  justify-content:stretch;
  width:200px;
  height:100vh;
  border:1px solid blue;
}
.item{
  flex-grow:1; 
  width:100px;
  border:1px solid red;   
}
&#13;
<h4>Red child divs will stretch to fill blue parent</h4>
<div class='container'>
  <div class='item'>One</div>
  <div class='item'>Two</div>
  <div class='item'>Three</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这可以通过绝对定位Flex容器来完成:

#flex {
   display: flex;
   align-content: center;
   position: absolute;
   top: 0; left: 0; right: 0; bottom: 0;
   flex-direction: column;
}

#flex > div:nth-child(1) {
    flex: 1;
}

#flex > div:nth-child(2) {
    flex: 1;
}

#flex > div:nth-child(3) {
     flex: 1;
}

Updated codepen