当我尝试将一个元素放在左上角而一个放在中间时,顶部元素不会一直向左移动.我该如何做到这一点?
.Aligner {
background-color: blue;
display: flex;
align-items: center;
justify-content: center;
height: 200px;
}
.Aligner-item {
max-width: 50%;
background-color: green;
}
.Aligner-item--top {
align-self: flex-start;
}Run Code Online (Sandbox Code Playgroud)
<div class="Aligner">
<div class="Aligner-item Aligner-item--top">…</div>
<div class="Aligner-item">…</div>
<div class="Aligner-item Aligner-item--bottom">…</div>
</div>Run Code Online (Sandbox Code Playgroud)
来自MDN:
flex-startFlex项的交叉开始边缘边缘用线的交叉起始边缘刷新.
这意味着align-self: flex-start;将top盒子的上边缘与flex盒子的上边缘(横轴的开头)对齐.
左/右值沿主轴.您可以在W3C规范中阅读更多相关信息:https://drafts.csswg.org/css-align/#align-self-property
实现所需布局的一种方法是使用position属性.
请注意,添加position将改变弹性行为; 如果你愿意的话,它就是一种"覆盖"属性.align-self绝对定位的框沿着包含块的块轴(在本例中为y-axis).
您可以在此处查看有关绝对定位的Flex项目的更多信息:http://www.w3.org/TR/css3-flexbox/#abspos-items
.Aligner {
background-color: blue;
display: flex;
align-items: center;
justify-content: center;
height: 200px;
position: relative; /* new */
}
.Aligner-item {
max-width: 50%;
background-color: green;
}
.Aligner-item--top {
align-self: flex-start;
left: 0; /* new */
top: 0; /* new */
position: absolute; /* new */
}Run Code Online (Sandbox Code Playgroud)
<div class="Aligner">
<div class="Aligner-item Aligner-item--top">…</div>
<div class="Aligner-item">…</div>
<div class="Aligner-item Aligner-item--bottom">…</div>
</div>Run Code Online (Sandbox Code Playgroud)