如何仅使一个柔韧性项目伸展而其他却不能保持其自然高度?

时间:2018-10-01 13:04:33

标签: html css css3 flexbox

我希望除last以外的所有flex项仅占据它们的正常高度,而最后一个flex-item占据flexbox的剩余高度(拉伸)。但是我无法做到这一点。

以下是我一直在尝试的方法:

  .parent {
        display: flex;
        flex-wrap: wrap;
        /*align-content: start;*/
        border: 1px solid green;
        height: 50vh
    }

    .child-height-auto {
        align-self: start;
        border: 1px solid red;
        width: 100%;
    }

    .child-height-strech {
        align-self: stretch;
        border: 1px solid blue;
        width: 100%;
    }
<div class="parent">
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-strech">I should occupy remaining height of the flexbox</div>
</div>

3 个答案:

答案 0 :(得分:2)

将flex的方向设置为column,并将flex-grow属性添加到最后一个元素。

  .parent {
        display: flex;
        flex-wrap: wrap;
        /*align-content: start;*/
        border: 1px solid green;
        height: 50vh;
        flex-direction: column;
    }

    .child-height-auto {
        align-self: start;
        border: 1px solid red;
        width: 100%;
    }

    .child-height-strech {
        align-self: stretch;
        border: 1px solid blue;
        width: 100%;
        flex-grow: 1;
    }
<div class="parent">
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-strech">I should occupy remaining height of the flexbox</div>
</div>

答案 1 :(得分:0)

尝试使用以下代码

.parent {
  display: flex;
  flex-wrap: wrap;
  border: 1px solid green;
  height: 50vh;
  flex-flow: column;
}
.child-height-auto {
  align-self: start;
  border: 1px solid red;
  width: 100%;
  flex-shrink: 1;
}
.child-height-strech {
  align-self: stretch;
  border: 1px solid blue;
  width: 100%;
  flex-grow: 1;
}
<div class="parent">
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-strech">I should occupy remaining height of the flexbox</div>
</div>

答案 2 :(得分:0)

首先,您应该添加flex-direction: column;并删除flex-wrap。然后,您可以为弹性项目的类分配不同的flex-grow参数(最后一个可能会增加,其他则不会)-见下文。

.parent {
        display: flex;
        flex-direction: column;
        border: 1px solid green;
        height: 50vh
    }

    .child-height-auto {
        align-self: start;
        border: 1px solid red;
        width: 100%;
        flex-grow: 0;
    }

    .child-height-strech {
        align-self: stretch;
        border: 1px solid blue;
        width: 100%;
        flex-grow: 1;
}
<div class="parent">
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-auto">I should occupy my normal height</div>
    <div class="child-height-strech">I should occupy remaining height of the flexbox</div>
</div>