【问题标题】:Position last flex item at the end of container将最后一个弹性项目放置在容器的末尾
【发布时间】:2016-02-28 17:22:28
【问题描述】:

这个问题涉及一个完全支持 css3 的浏览器,包括 flexbox。

我有一个 flex 容器,里面有一些项目。它们都适合 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>

【问题讨论】:

标签: css flexbox


【解决方案1】:

Flexible Box Layout Module - 8.1. Aligning with auto margins

弹性项目的自动边距与块流中的自动边距的效果非常相似:

  • 在计算弹性底数和弹性长度时,自动边距被视为 0。

  • 在通过justify-contentalign-self 对齐之前,任何正的可用空间都会分配到该维度的自动边距。

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

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

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>

【讨论】:

  • 啊完美,真不敢相信我错过了!特别尴尬,因为我完全知道 using-margin-auto-to-center-vertically 技巧并一直使用它
  • @j08691 我没有正式解释它的为什么起作用,但它类似于您如何使用margin: 0 auto 进行水平居中。 Flexbox 项目尊重边距,我相信margin: auto 本质上会在同级之间尽可能多地放置项目。见:w3.org/TR/css-flexbox-1/#auto-margins
  • @jo8691 如果我没记错的话,弹性项目上的margin: auto 告诉它在那个方向上创建尽可能多的空间。
  • The spec says Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.
  • 我正在尝试了解有关 flexbox 的更多信息,因此很高兴看到描述此行为的参考资料。特别是它也是有意的,而不是怪癖或副作用。
【解决方案2】:

这种弹性盒原理也适用于水平方向

在计算弹性底数和弹性长度时,自动边距 被视为 0。
在通过 justify-content 对齐之前和 align-self,任何正的可用空间都分配到自动边距 那个维度。

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

.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

【讨论】:

  • 不确定为什么这确实有效,但它帮助我完成了一个项目。
  • 如果我需要所有项目都在中心,最后一个在右侧怎么办?
  • 这里有一个变体,但有居中的项目:stackoverflow.com/a/59405567/2394994
猜你喜欢
  • 1970-01-01
  • 2020-04-13
  • 2020-10-06
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 2018-12-27
  • 2020-12-13
  • 1970-01-01
相关资源
最近更新 更多