Search code examples
csshtmlcenter

Vertical Aligned Div


Does anyone in here knows how to make a div go to the center of the page (vertically) no matter the screen resolution or window size of the user? As an example, the login page of Instagram. If you make your window smaller, the div will keep floating at the center until it gets to the top. I made that, but the problem was that when the user kept making the window smaller, the div was actually going out of the user window (to the top).

Here is the Instagram login page for the example: https://instagram.com/accounts/login/

And here is my page for the other example: http://www.farespr.com

Would appreciate an answer =)

EDIT: This is my main div code:

#wrapper2{
    width: 960px;
    height: 530px;
    top: 50%;
    margin-top: -280px;
    margin-right: auto;
    margin-left: auto;
    position: fixed;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    border: 1px solid #dcdcdc;
    box-shadow: 0px 0px 5px 3px #f0f0f0;
    background: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#efefef));
    background: -moz-linear-gradient(top,  #fafafa,  #efefef);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fafafa', endColorstr='#efefef');
}

Solution

  • This will work for any size div.

    demo: http://jsfiddle.net/BxLhz/

    HTML:

    <div></div>
    

    CSS:

    div {
        width: 100px;
        height: 100px;
        background-color: #cc333;
    
        position: absolute;
        top:0;
        bottom: 0;
        left: 0;
        right: 0;
    
        margin: auto;
    }
    

    UPDATE:

    demo: http://jsfiddle.net/Ha4PU/

    CSS:

    #wrapper {
        width: 200px;
        height: 200px;
        background-color: #ccc333;
    
        position: absolute;
        top:0;
        bottom: 0;
        left: 0;
        right: 0;
    
        margin: auto;
    }
    
    @media only screen and (max-height : 200px) {
        #wrapper {
            position: relative;
        }
    }
    

    where max-height = height of .wrapper