treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Center Center a Div

  • 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.

  • 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 :)

  • You can do it with CSS. Just search for it on here, there's an article about "vertically centering in the unknown".

  • Ahhh, I think I remember that article now.

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

  • 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:

      <div class="holder">
         <div></div>
      </div>
    
    .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 (: