代码之家  ›  专栏  ›  技术社区  ›  user3137124

当“flex direction”为“column”时,如何将div与顶部对齐?[副本]

  •  1
  • user3137124  · 技术社区  · 7 年前

    我在一个容器中有两个div标签。我想使用flex-box并将第一个div标记与顶部对齐,另一个相对于容器居中。我该怎么做?

    使用 align-items: flex-start 仅在“flex direction”为“column”时将其向左移动。将其移至顶部的等效css是什么?

    代码笔: https://codepen.io/GMSg68/pen/aGpOpG

    .box {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 500px;
      border: 1px solid blue;
    }
    
    .box div {
      width: 100px;
      height: 100px;
      border: 1px solid darkgray;
    }
    
    .box div:nth-child(1) {
      /*  How do I push the first div tag to the top? */
      background-color: lightgray;
    }
    
    .box div:nth-child(2) {
      background-color: lightblue;
    }
    <div class="box">
      <div>One</div>
      <div>Two</div>
    </div>
    1 回复  |  直到 7 年前
        1
  •  2
  •   Willans    7 年前

    向第n个子(2)div添加margin top和bottom auto。然后添加-50%的Y变换以将其与中心对齐。这假设两个div的高度相同。

    .box div:nth-child(2){
      background-color: lightblue;
      margin-top: auto;
      margin-bottom: auto;
      transform: translateY(-50%);
    }