css - 将最后一个 flex 元素放在容器的末尾

标签 css flexbox

这个问题涉及一个完全支持 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>

最佳答案

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 来分配其他元素和最后一个元素之间的空间。

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

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>

vertical example


同样,您也可以使用 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>

horizontal example

关于css - 将最后一个 flex 元素放在容器的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33924655/

相关文章:

css - 如何在 Html ActionLink 中设置工具提示的样式

css - 在下拉菜单中创建水平和垂直菜单

html - 让包裹的 flexbox 的 child 挤进 parent 的高度

html - 我怎样才能将我的 flex 元素展开到超过容器的宽度?

css - 如何在多行中获得 33.33% 宽度的 flex div?

javascript - 包裹在标签中时会触发后面的单击事件

javascript - 根据单元格值设置 SlickGrid 单元格样式

html - Flexbox 文本和跨度单元格未按预期运行

html - 在 ExtJS 中使用 CSS !important setFieldStyle()

html - 不能强制 flex 列容器到全高