【问题标题】:Share same item height with flexbox与 flexbox 共享相同的项目高度
【发布时间】:2015-01-31 13:55:25
【问题描述】:

我的笔: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% 在 body,html 标签中!

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

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

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

    【讨论】:

    • funny...我的结果相同,但 css 不同。为什么我的也有效?我不喜欢 flexbox 有多种方式来做某事...codepen.io/helloworld/pen/yyoWja
    • @Pascal,justify-context 的默认属性是stretch,所以你可以放心地从我的回答中省略它。那么我的回答和你的回答很像。顺便说一句,我自己的偏好是指定默认值,即使它们不是必需的——只是为了在我稍后查看代码时清楚起见。祝你的项目好运!
    【解决方案2】:

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

    #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

    【讨论】:

    • 那你说的“总是占据整个屏幕的高度是什么意思?”?
    猜你喜欢
    • 2017-06-19
    • 2016-05-11
    • 2018-01-30
    • 2020-11-10
    • 2021-11-14
    • 2016-01-15
    • 2022-01-21
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多