【问题标题】:Vertically aligning two flex items [duplicate]垂直对齐两个弹性项目[重复]
【发布时间】:2016-01-06 03:01:54
【问题描述】:

我有一个弹性容器 .container 和两个弹性项目:item-oneitem-two。我想将第一个项目垂直居中并将第二个项目放在底部。

我不知道如何在这种情况下垂直对齐第一项。

HTML:

<div class="container">
  <div class="item-one">Item One</div>
  <div class="item-two">Item Two</div>
</div>

CSS:

html, body {
  height: 100%;
  margin: 0;
}

.container {
  width: 500px;
  margin: 0 auto;
  border: 5px solid orange;
  height: 100%;

  /* Flex properties */
  display: flex;
  flex-wrap: wrap;  
  align-items: center;
  justify-content: center;
}

.item-one {
  border: 5px solid yellow;
  flex-basis: 500px;    
}

.item-two {
  border: 5px solid red;
  align-self: flex-end;
}

CodePen

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    您可以使用auto margins 来对齐这样的元素。这将允许您在auto 边距的方向上分配任何正的可用空间。

    在这种情况下,您可以将 flex-direction 更改为 column 以使 flexbox 项目垂直流动。然后你可以在第一个 flexbox 项目上设置 margin-top: auto/margin-bottom: auto 以使其垂直居中并确保其上方和下方的空间相等。这样做会将第二个项目推到底部:

    Updated Example

    html, body {
      height: 100%;
      margin: 0;
    }
    .container {
      width: 500px;
      margin: 0 auto;
      border: 5px solid orange;
      height: 100%;
      display: flex;
      flex-direction: column
    }
    .item-one {
      border: 5px solid yellow;
      margin: auto 0;
    }
    .item-two {
      border: 5px solid red;
      margin: 0 auto;
    }
    <div class="container">
      <div class="item-one">Item One</div>
      <div class="item-two">Item Two</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 2018-04-01
      • 2013-09-23
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多