【问题标题】:How to vertically align one of the flex element childs [duplicate]如何垂直对齐一个flex元素子元素[重复]
【发布时间】:2017-09-15 15:21:27
【问题描述】:

我在一个带有flex-direction:column 的弹性容器中有 3 个垂直居中的 div,我需要将第三个 div 放在容器的底部。

这是我想要的解释:https://jsfiddle.net/tom8p7be/

我该怎么做?

【问题讨论】:

  • 您是否希望 2 个居中的居中位置的可用空间一直到最后一个 div 或其父级?

标签: css flexbox


【解决方案1】:

您可以在第一个和最后一个子 div 上添加 margin-top: auto。当您将 margin-top: auto 添加到最后一个子 div 时,它会将那个 div 推到父级的末尾,但它也会将其他两个 div 推到父级的顶部。这就是为什么您还需要将 margin-top: auto 添加到第一个子 div,这会将它们定位在从顶部到最后一个子 div 的空间中心。

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}
.container div {
  margin: 5px;
  padding: 5px 10px;
  border: 1px solid;
}
.container > div:last-child,
.container > div:first-child{
  margin-top: auto;
}
<div class="container">
    <div>This div should be vertically centered</div>
    <div>This one too</div>
    <div>And this div shoud be placed at the bottom of the flex container</div>
</div>

【讨论】:

  • 谢谢!它对我有用。
猜你喜欢
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 2018-09-24
  • 2018-03-30
相关资源
最近更新 更多