Flex框:填充剩余空间,但证明内容中心是合理的

问题描述 投票:4回答:2

我希望实现如下所示的布局:

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无法解决这个问题并且需要破解,但我会感谢任何能够提出最简单解决方案的人。

谢谢。

html css flexbox
2个回答
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>

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>
© www.soinside.com 2019 - 2024. All rights reserved.