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

底部对齐父div内的2个div(同时保持一个子div在另一个子div的顶部)

  •  0
  • WomenWhoCode  · 技术社区  · 5 年前

    我有三个div:

    <div class="parent"> 
      <div class="child1"> </div>
      <div class="child2"> </div>
    </div>
    

    CSS:

    .parent {
      height: 500px;
      width: 500px;
      position: relative;
    }
    
    .child1, .child2 {
      height: 100px;
      width: 100px;
    }
    

    我需要对齐 child2 div位于底部 .parent div,而 child1 div应该在顶部 儿童2 div。

    所以,两者 儿童1 儿童2 应该与父div底部对齐,但是 儿童1 应该在上面 儿童2 .

    我怎样才能做到这一点?如果只有一个子div,可以通过设置来实现 position: absolute; bottom:0 ,但我无法确定是否有2个子div,并且一个子div应该位于另一个子div之上。

    1 回复  |  直到 5 年前
        1
  •  2
  •   khan    5 年前

    您可以在以下设备上使用Flexbox .parent 并应用以下样式:

    .parent {
      /* Introduce Flexbox */
      display: flex;
    
      /* Establishes the y-axis as the main axis.
         This displays the children from top to bottom */
      flex-direction: column;
    
      /* Packs the children from the end of the main axis */
      justify-content: flex-end;
    }
    

    .parent {
      height: 500px;
      width: 500px;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      border: 1px solid black;
    }
    
    .child1,
    .child2 {
      height: 100px;
      width: 100px;
    }
    
    .child1 {
      background: red;
    }
    
    .child2 {
      background: blue;
    }
    <div class="parent">
      <div class="child1"> </div>
      <div class="child2"> </div>
    </div>