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

Kar*_*ell 4 html css flexbox

我想要实现如下布局:

弹性框目标

换句话说,最后一个项目占据了“剩余空间”,而其他项目居中,就好像项目3 与项目1和2的大小相同。我可以最接近的布局是:

在此处输入图片说明

我也尝试过设置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? */
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

可能仅靠flex-box不能解决这个问题,并且需要破解,但是我将感谢能够提出最简单解决方案的任何人。

谢谢。

Jak*_*ake 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)