Center flex items while positioning one in corner
I've started to experiment with flexbox lately, but still can't wrap my head around some things.
I am trying to create a simple layout with three flex items (children). The container is set to flex-direction: column
and all the flex items are centered horizontally and vertically.
I would like one of the flex items to be positioned at the top left corner. Basically like I am using position: absolute
with top: 30px; left: 30px;
top: 30px; left: 30px;
.
I know that align-self
is used to override styles for each flex item, but I can't get it to work.
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>
You can position a flex item in a corner, while centering sibling flex items, with auto
margins and an invisible flex item.
HTML (add one flex item)
<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 (relevant sections)
.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
NOTE: This centering and positioning solution will work when all flex items are equal height. If flex items vary in height (or width, when flex-direction
is row
), then true centering will be off and absolute positioning may be the better solution.
For an absolute positioning method, and other centering and positioning options, see this answer:
上一篇: 使容器缩小