在弹性容器中居中单个项目
center individual item in flex container
我有一个这样的 flexbox 结构:
<div class="container">
<div class="flex-child-1">
<div class="sub-1">
sub-item 1
</div>
<div class="sub-2">
sub item 2
</div>
</div> //end item 1
<div class="flex-child-2">
item 2
</div> // end item 2
</div> // end container
我希望在其容器内垂直居中 sub-2
:flex-child-1
(它本身就是一个 flexbox 子项)。请注意,我不想居中 sub-1
。想法?
flexbox specification allows for absolutely-positioned flex children,它使您能够将单个弹性项目居中:
CSS
.flex-child-1 {
display: flex;
height: 480px; /* for demo purposes */
position: relative; /* establish nearest positioned ancestor for abs. positioning */
}
/* for vertical and horizontal centering */
.sub-2 {
position: absolute;
left: 50%; /* relative to nearest positioned ancestor */
top: 50%; /* relative to nearest positioned ancestor */
transform: translate(-50%, -50%); /* relative to element's height & width */
}
/* for vertical centering only */
.sub-2 {
position: absolute;
left: 0%;
top: 50%;
transform: translate(0, -50%);
}
我有一个这样的 flexbox 结构:
<div class="container">
<div class="flex-child-1">
<div class="sub-1">
sub-item 1
</div>
<div class="sub-2">
sub item 2
</div>
</div> //end item 1
<div class="flex-child-2">
item 2
</div> // end item 2
</div> // end container
我希望在其容器内垂直居中 sub-2
:flex-child-1
(它本身就是一个 flexbox 子项)。请注意,我不想居中 sub-1
。想法?
flexbox specification allows for absolutely-positioned flex children,它使您能够将单个弹性项目居中:
CSS
.flex-child-1 {
display: flex;
height: 480px; /* for demo purposes */
position: relative; /* establish nearest positioned ancestor for abs. positioning */
}
/* for vertical and horizontal centering */
.sub-2 {
position: absolute;
left: 50%; /* relative to nearest positioned ancestor */
top: 50%; /* relative to nearest positioned ancestor */
transform: translate(-50%, -50%); /* relative to element's height & width */
}
/* for vertical centering only */
.sub-2 {
position: absolute;
left: 0%;
top: 50%;
transform: translate(0, -50%);
}