我试过用CSS Grid和CSS Flex来实现,但不能完全实现。
要求:
我有一个容器,里面有多个元素, 每个元素都有顶部、中心和底部的配置作为垂直对齐方式。 所有顶部元素都应该出现在顶部,所有中心元素都应该出现在父级的中心,所有底部元素都应该出现在父级的底部。
元素是动态的,意味着可以有任意数量的元素,每个元素可以有任意位置(顶部、中心、底部)。
给用户的唯一限制是他们将按顺序添加元素,这意味着首先他将添加顶部元素,然后是居中元素,然后是底部元素。
<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>
最佳答案
您可以使用 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>
关于css - 使用 CSS 在不同位置垂直对齐多个堆叠元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830530/