居中弹性项目,同时将一个项目放在角落

Center flex items while positioning one in corner

我最近开始尝试使用 flexbox,但仍然无法解决一些问题。

我正在尝试创建一个包含三个弹性项目(子项)的简单布局。容器设置为 flex-direction: column,所有弹性项目水平和垂直居中。

我希望其中一个弹性项目位于左上角。 基本上就像我使用 position: absolutetop: 30px; left: 30px;.

我知道 align-self 用于覆盖每个 flex 项目的样式,但我无法让它工作。

Here is the fiddle

您可以使用 pseudo 元素和 flex & order 规则:http://jsfiddle.net/49eghxna/2/

.flex-container {
    max-width:80%;
    margin: 100px auto;
    height:600px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #1E5655
}
.flex-container:before, .flex-container:after {
    content:'';
    flex:1;/* will use and share all space avalaible if no values set to others */
}
.flex-container:before {
    order:2
}
.flex-container:after {
    order:5
}
.flex-item {
    width:300px;
    height:50px;
    background-color:#fff;
}
.flex-item:nth-of-type(2) {
    background-color: #eee;
    order:3;
}
.flex-item:nth-of-type(3) {
    background-color: #FFD454;
    order:4
}
.flex-item:nth-of-type(1) {
    align-self: flex-start;
    order:0;
}
<div class="flex-container">
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
</div>

您可以将弹性项目放在角落,同时将同级弹性项目居中, 和一个不可见的弹性项目。

HTML(添加一个弹性项目)

<div class="flex-container">
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div><!-- invisible flex item for balance -->
</div>

CSS(相关部分)

.flex-item:nth-of-type(1) { margin-bottom: auto; margin-right: auto; }
.flex-item:nth-of-type(2) { }
.flex-item:nth-of-type(3) { }
.flex-item:nth-of-type(4) { margin-top: auto; visibility: hidden; }

DEMO

注意:当所有 flex 项目高度相同时,此居中和定位解决方案将起作用。如果 flex 项目的高度(或宽度,当 flex-directionrow 时)不同,那么真正的居中将关闭,绝对定位可能是更好的解决方案。

对于绝对定位方法以及其他居中和定位选项,请参阅此答案: