代码之家  ›  专栏  ›  技术社区  ›  Ronit Mukherjee

使用CSS在不同位置垂直对齐多个堆叠项

  •  0
  • Ronit Mukherjee  · 技术社区  · 7 年前

    要求:

    每个项目都有一个顶部、中心和底部的垂直对齐配置。 所有顶部项目应显示在顶部,所有中心项目应显示在中心,所有底部项目应显示在父项的底部。

    项目是动态的,意味着可以有任何数量的项目,每个项目可以有任何位置(顶部、中心、底部)。

    enter image description here

    <div class="parent">
        <div class="child top"> Item 1</div>
        <div class="child top"> Item 2</div>
        <div class="child center"> Item 3</div>
        <div class="child center">Item 4</div>
        <div class="child bottom"> Item 5</div>
        <div class="child bottom"> Item 6</div>
      </div>
    </div>
    0 回复  |  直到 7 年前
        1
  •  0
  •   Temani Afif    7 年前

    你可以用 order 以及伪元素。诀窍在于,两个伪元素将位于顶部/中心和底部/中心之间,并将填充所有空间。也可以对元素进行置乱,HTML顺序无关紧要:

    .parent {
      height:500px;
      border:2px solid;
      display:flex;
      flex-direction:column;
    }
    .parent > * {
      padding:10px;
      background:red;
      color:#fff;
      text-align:center;
    }
    
    .top { order:1}
    .parent:before {
      content:"";
      order:2;
      flex:1
    }
    .center { order:3}
    .parent:after {
      content:"";
      order:4;
      flex:1
    }
    .bottom { order:5}
    <div class="parent">
        <div class="child center"> Item 3</div>
        <div class="child top"> Item 1</div>
        <div class="child center">Item 4</div>
        <div class="child bottom"> Item 5</div>
        <div class="child bottom"> Item 6</div>
        <div class="child top"> Item 2</div>
        <div class="child bottom"> Item 7</div>
        <div class="child top"> Item 8</div>
    </div>

    既然你说秩序会得到尊重的另一个想法是 + 选择器和自动边距:

    .parent {
      height:500px;
      border:2px solid;
      display:flex;
      flex-direction:column;
    }
    .parent > * {
      padding:10px;
      background:red;
      color:#fff;
      text-align:center;
    }
    
    .top + .center {
      margin-top:auto;
    }
    
    .center + .bottom {
      margin-top:auto;
    }
    <div class="parent">
        <div class="child top"> Item 1</div>
        <div class="child top"> Item 2</div>
        <div class="child center"> Item 3</div>
        <div class="child center">Item 4</div>
        <div class="child bottom"> Item 5</div>
        <div class="child bottom"> Item 6</div>
    </div>
    推荐文章