将灵活容器中的单个项目居中

时间:2015-10-18 17:05:36

标签: html css css3 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-2flex-child-1(它本身就是一个flexbox子容器)。请注意,我不想以sub-1为中心。想法?

1 个答案:

答案 0 :(得分:0)

flexbox specification允许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%);
}

DEMO:http://jsfiddle.net/24tpsvb9/6/