[TUT] Center An Object Vertically and Horizontally

Position both Vertically and Horizontally?

This method will require absolute positioning, but don't worry its not hard. Let's start up by creating some dummy markup to test it.

The Markup



   

With this we simply created to containers, one inside the other so we can practice centering it. Now lets write the CSS


html,
body{
   width:100%;
   height:100%;
}
div#responsive-box{
   width:100%;
   height:100%;
   position:relative;
   background-color:red;
}
div#centered-box{
   height:200px;
   width:200px;
   position: absolute;
   top:0;
   left:0;
   bottom: 0;
   right:0;
   margin: auto auto;
   background-color:blue;
}

If you saw my last post, you will know that first few lines of CSS are just there to allow me to create a div the full size of the viewport. Then we gave the responsive box both a width and a height of 100% so it will be responsive and we can see how the other box will remain centered at all times.

By positioning absolute zero to all sides we are telling the browser that we want our box to touch all of them, but that's not possible due to the size.

We then asked it to margin auto auto, which it then takes in and centers it dead center since we also wanted it to be touching all sides.

Margin auto vertically will usually not work, but when used with this hack it will.