Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center a div with variable height within a div that is 100% of the viewport

I know it looks like a question that has been asked many times, but I just couldn't find the solution to that very specific situation.

Here's the basic wireframe of my layout :

enter image description here

Basically, I've got a few divs with different backgrounds that take 100% width and 100% height of the browser window. Within each and every of them is another div that takes 50% width of its parent but has a variable height, depending on its content.

I'd like all of these divs-within-a-div to be vertically align. Now, I've read that putting a display:table-cell and a vertical-align:middle on the parent should work, but in this case it just seems to mess things up. :-/

My code:

<head>
<style>
     html, body {
            height: 100%;
        }
        body > div {
            width: 100%;
            height: 100%;
            background-size: cover;
        }

        .centered {
            width: 50%;
            margin: 0 auto;
            background: rgba(0,0,0,0.4);
            padding: 50px 0 30px 0;
        }
</style>
</head>
        <body>

            <div id="pic_1">
                    <div class="centered">content</div>
            </div>

            <div id="pic_2">
                    <div class="centered">content</div>
            </div>

            <div id="pic_3">
                    <div class="centered">content</div> 
            </div>  

        </body>

Thanks for your help!

like image 235
Tom S. Avatar asked Jan 01 '13 19:01

Tom S.


1 Answers

Set a grandparent element to be display:table; height:100% and the parent element to be display:table-cell; vertical-align:middle.

See "Method 1" here for an example.

Also, note that your markup should not use class="centered"; use a semantic class name instead.

like image 184
Phrogz Avatar answered Nov 15 '22 08:11

Phrogz