Ed_
Ed_

Reputation: 19098

Vertically centering content within a space-filling flex box

I'm trying to vertically center the content within two flex boxes in a column layout.

I have created a simplified Fiddle to demonstrate.

HTML:

<div id='container'>
    <div id= "top">
        some content!
    </div>
    <div id= "bottom">
        some content!
    </div>
</div>

CSS:

#container{
    display: -webkit-flex;
    width:100%;
    height:300px;
    -webkit-flex-direction: column;
    -webkit-justify-content: space-around;
    background-color: gray;
}
#container div{
    text-align:center;
    background-color:red;
    //-webkit-flex: 1; //uncomment to see 2nd option
    //vertical-align: middle; //doesn't work
}

I want the inner DIVs to stretch vertically to fill the remaining space. I can do this by un-commenting the flex value, but when I do that the content is aligned to the top. I tried vertical-align but this didn't work (I didn't expect it to!)...

Because my application with this has a container with dynamic height, I can't use fixed margins or padding to sort this problem.

Is there a way to do this? Perhaps I have to make the inner divs themselves flex containers, but this seems a bit messy..

Upvotes: 1

Views: 4724

Answers (1)

cimmanon
cimmanon

Reputation: 68319

You don't have much choice here. The vertical-align property only works on inline or table-cell elements. You're really only adding one extra property and shuffling two you already have.

http://jsfiddle.net/bHNC9/1/

#container{
    display: -webkit-flex;
    width:100%;
    height:300px;
    -webkit-flex-direction: column;
    background-color: gray;
}
#container div{
    text-align:center;
    background-color:red;
    -webkit-flex: 1;
    display: -webkit-flex;
    -webkit-align-items: center;
    -webkit-justify-content: center;
}

Upvotes: 5

Related Questions