CSS: vertical and horizontal centering boxes

CSS allows you to center an element within the viewport by using absolute positioning and negative margins. It works this way: you specify the width and the height of an element, then you set the top and left properties to 50% and then use negative values for the top and left margins by specifying the half of the height and width, respectively. So if your box is 400 pixels wide and 300 pixels tall, you can write the following:

#test {
 width: 400px;
 height: 300px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -150px 0 0 -200px;
}

150 is the half of the height of the element and 200 is the half of its width. The major drawback with these technique is that you always have to specify a dimension on the element in question. For example, you can simply set an height and only center it vertically:

#test {
   height: 300px;
   position: absolute;
   top: 50%;
   left: 0;
   margin: -150px 0 0 0;
}

Again, this technique is useful when at least one dimension is known in advance.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.