将最后一个弹性项目放在容器的末尾

Position last flex item at the end of container

此问题涉及具有完整 css3 支持(包括 flexbox)的浏览器。

我有一个弹性容器,里面有一些物品。它们都适合 flex-start,但我希望 last .end 项目适合 flex-end。有没有不修改 HTML 且不求助于绝对定位的好方法?

.container {
  display: flex;
  flex-direction: column;
  outline: 1px solid green;
  min-height: 400px;
  width: 100px;
  justify-content: flex-start;
}
p {
  height: 50px;
  background-color: blue;
  margin: 5px;
}
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p class="end"></p>
</div>

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

因此您可以使用 margin-top: auto 在其他元素和最后一个元素之间分配 space。

这会将最后一个元素放在底部。

p:last-of-type {
  margin-top: auto;
}

.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}
<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>


同样,您也可以使用margin-left: automargin-right: auto水平对齐。

p:last-of-type {
  margin-left: auto;
}

.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>

这个 flexbox 原则也适用于水平方向

在计算 flex bases 和 flexible lengths 时,auto margins 被视为 0。
在通过 justify-content 和对齐之前 align-self,任何正的 free space 都分配给 auto margins in 那个维度。

为最后一项设置自动左边距即可。

.last-item {
  margin-left: auto;
}

代码示例:

.container {
  display: flex;
  width: 400px;
  outline: 1px solid black;
}

p {
  height: 50px;
  width: 50px;
  margin: 5px;
  background-color: blue;
}

.last-item {
  margin-left: auto;
}
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p class="last-item"></p>
</div>

Codepen Snippet

这对于桌面页脚非常有用。

正如 Envato 在此处使用公司徽标所做的那样。

Codepen Snippet