弹性框:填满剩余空间,但证明内容中心合理

时间:2019-04-23 07:32:20

标签: html css flexbox

我想要实现如下所示的布局:

flex box goal

换句话说,最后一个项目占用了“剩余空间”,而其他项目居中 似乎项目3与项目1的尺寸相等,并且2.我最接近的是这个布局:

enter image description here

我还尝试在最后一项设置height: 100%,这当然不起作用,因为这会将项目1和2推到顶部。这是我不知道如何完成的代码片段:

/* Default values are skipped */
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.item {
   background: red;
}

.item-fill {
   background: yellow;
   /* What should go in here? */
}
<div class="container">
  <div class="item">
  First item
  </div>
  <div class="item">
  Second item
  </div>
    <div class="item-fill">
  Third item which should fill up the rest of the parent space without pushing the first and second item upwards
  </div>
</div>

这可能无法单独使用flex-box来解决,需要破解,但我感谢任何提出最简单解决方案的人。

谢谢。

2 个答案:

答案 0 :(得分:5)

只需添加一个值为flex-grow: 1;的伪元素(在容器中的其他项目之前),并将相同的flex-grow值设置为.item-fill

伪元素(此处为.container:before)将尽可能多地填充容器的顶部,而其他值为flex-grow的元素将填充其余部分。其他两个项目将与它们的内容一样小。

/* Default values are skipped */

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.container:before {
    content: "";
}

.container:before,
.item-fill {
    flex: 1;
}

.item {
   background: red;
}

.item-fill {
   background: yellow;
}
<div class="container">
  <div class="item">
  First item
  </div>
  <div class="item">
  Second item
  </div>
    <div class="item-fill">
  Third item which should fill up the rest of the parent space without pushing the first and second item upwards
  </div>
</div>

答案 1 :(得分:0)

为您的flex-grow类尝试item-fill

flex-grow属性指定相对于同一容器内其余柔性项目而言,该项目将增长多少。

* {
    box-sizing: border-box;
    position: relative;
}

.container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.item {
    background: red;
}

.item-fill {
    background: yellow;
    display: flex;
    flex-grow: 1;
}
<div class="container">
    <div class="item">
        First item
    </div>
    <div class="item">
        Second item
    </div>
    <div class="item-fill">
        Third item which should fill up the rest of the screen space without pushing the first and second item upwards
    </div>
</div>