我是 Flexbox 的新手,想对齐按钮,但我不知道如何仅使用 Flexbox 来处理同一行上居中对齐按钮和右对齐按钮的常见情况。
但是,我找到了一种方法,它使用与右对齐元素长度相同的不可见左对齐元素和 flex justify-content
with space-between
使中间元素在行中居中。
Flexbox 有更直接的方法吗?
.flexcontainer {
display: flex;
justify-content: space-between;
width: 500px;
height: 200px;
}
.iteminvisible {
flex: 0 1 auto;
width: 100px;
height: 100px;
visibility: hidden;
}
.itemcenter {
flex: 0 1 auto;
width: 150px;
height: 100px;
}
.itemright {
flex: 0 1 auto;
width: 100px;
height: 100px;
}
<div class="flexcontainer">
<div class="iteminvisible">Other</div>
<div class="itemcenter">One</div>
<div class="itemright">Other</div>
</div>
如您的问题所述,将 justify-content: space-between
与不可见的 flex 元素一起使用是实现所需布局的好方法。请注意,如果左右元素长度相等(see demo),中间元素只能居中。
您可能要考虑的另一个解决方案涉及 auto
margins和 absolute positioning .这种方法的两个好处是不需要额外的标记,并且无论元素大小如何都可以实现真正的居中。一个缺点是居中的元素从 document flow 中移除。 (这对您来说可能重要也可能不重要)。
.flexcontainer {
display: flex;
justify-content: flex-start;
/* adjustment */
position: relative;
/* new */
width: 500px;
height: 200px;
}
.itemcenter {
flex: 0 1 auto;
width: 150px;
height: 100px;
position: absolute;
/* new */
left: 50%;
transform: translateX(-50%);
}
.itemright {
flex: 0 1 auto;
width: 100px;
height: 100px;
margin-left: auto;
/* new */
}
<div class="flexcontainer">
<div class="itemcenter">One</div>
<div class="itemright">Other</div>
</div>
此处有更多详细信息:Methods for Aligning Flex Items along the Main Axis (见方框 #62-78)。