使用flex项目作为flex容器

5

我想使用flexbox来进行列布局,但是我希望前 n - 1 个flex项目固定在顶部,而第 n 个flex项目固定在主要的flex容器区域的底部。

我通过使用第 n 个flex项目作为新的flexbox/flex容器,并使用 justify-content: flex-end 来解决这个问题,但我找不到任何这样做的示例 - 所以根据标准,这是正确/可接受的解决方案吗?如果不是,那么我该如何使用flexbox解决这个问题呢?

以下是一个快速示例:

.flex-container {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  width: 300px;
  height: 240px;
  background-color: Silver;
}
.flex-container-bottom {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  width: 300px;
  height: 240px;
  background-color: orange;
  -webkit-justify-content: flex-end;
  -ms-flex-pack: end;
  justify-content: flex-end;
}
.flex-item {
  background-color: DeepSkyBlue;
  width: 100px;
  height: 100px;
  margin: 5px;
}
.flex-item-bottom {
  background-color: red;
  width: 100%;
  height: 50px;
}
<div class="flex-container">
  <div class="flex-item">flex item 1</div>
  <div class="flex-item flex-container-bottom">
    <div class="flex-item-bottom">flex item 2</div>
  </div>
</div>

3个回答

5
规范在这方面并不是非常清晰,但它表明,“flex容器的每个流动子元素都变成了一个flex项目,并且直接包含在flex容器中的每个连续文本运行都被包装在一个匿名的flex项目中。” 这似乎意味着如果我将一个flex容器放置在另一个flex容器中,即使没有明确定义,内部flex容器也会成为其包含flex容器的隐式弹性项目。规范的示例1显示了一个flex容器内部有一个flex容器,并假设它是合法的语法,那么我的用例也可能是合法的,但带有示例1的部分被标记为非规范性... (╯°□°)╯︵ ┻━┻...此时,我只能假定这是正确的。

2
规范对此非常明确:是允许的。 - Oriol
如果你有更好的答案,请随意发表,我会很高兴地接受它作为答案 - 我没有时间对标准进行详细梳理。 - Jordan
我并没有更好的答案,但我认为你回答中的引用已经足够清晰了。概述部分是非规范性的,因为它只是以下各节的摘要,而这些才是“真正”的规范。 - Oriol

3
很难说你使用 flex-end 是错误的,因为你得到了期望的效果,但有一种更简单的方法。

尝试使用:

.flex-container{
   display: flex;
   justify-content: space-between;
   flex-direction: column;
}

justify-content: space-between;会让你的弹性项目尽可能地在容器内展开。

这是我在使用flexbox时经常使用的参考指南:https://css-tricks.com/snippets/css/a-guide-to-flexbox/


2
您可以尝试这个方法,它会使最后一个项粘在父容器底部。
.flex-container{
    position:relative;
   }
 .flex-item-bottom{
    position:absolute;
    bottom:0;
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接