Grow your CSS skills. Land your dream job.

Center Center a Div

  • # December 10, 2012 at 6:46 pm

    So I’m trying to center a div on the page (Horizontally _and_ Vertically). This is what i did but it only centered it:

    div{
    width:500px;
    margin-left:auto;
    margin-right:auto;
    margin-top:auto;
    margin-bottom:auto;
    }

    Any suggestions? Any help is appreciated.

    # December 10, 2012 at 6:51 pm

    Hmm, I’m not sure whether it’s possible with CSS alone. Maybe you’d need a JS solution also to calculate the height of the browser window and center it that way somehow.

    Maybe it can be done with CSS alone, if it is then I await some answers :)

    # December 10, 2012 at 6:57 pm

    You can do it with CSS. Just search for it on here, there’s an article about “vertically centering in the unknown”.

    # December 11, 2012 at 3:40 am

    Ahhh, I think I remember that article now.

    # December 11, 2012 at 4:34 am

    [Vertical Align](http://codepen.io/alexmccabe/pen/ydwum “vertical yo”)

    # December 11, 2012 at 12:47 pm

    Originally went for a fairly long winded js solution. But the ghosting method on the vertically centering in the unknown page is spectacular.

    # December 12, 2012 at 6:25 am

    ..

    # December 12, 2012 at 6:28 am

    About the horizontal centering you may use margin:0 auto; only if you set some width of your div element; You may also use more clever way with position relative. I Use this approach when have to centering ul elements which is with display:inline by default.
    The idea is:

    .holder {
    float: left;
    left: 50%;
    position: relative;
    }
    .holder > div {
    float: left;
    left: -50%;
    position: relative;
    }

    the parent of .holder also must be with position relative.
    You may use this approach for vertical centering.
    I hope you catch the idea (:

Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".