Home > Web > Centering a DIV using CSS

Centering a DIV using CSS

Using DIVs instead of TABLEs and CSS formatting should be a good practice for any web developer/designer. But how would you center a DIV? If you’ll do a page and you’ll want to optimize the contents for a specific resolution and center (this should be default and desired way) the contents then this will be one of your first CSS questions.

The answer is very easy. Supposing you have the following HTML fragment

    <div id="content">My page</div> 

Then centering the content DIV will be made using the following CSS code:

    text-align: center; 
    min-width: 800px; 

DIV#content { 
    margin-left: auto; 
    margin-right: auto; 
    width: 800px; 
    text-align: left; 

Now let’s see what exactly the code is doing. Centering the div horizontally is pretty easy. Simply specify a width (this is mandatory, otherwise it won’t work – usually it will be the resolution for which you want to optimize) and then set the right and left margin widths to auto.

Unfortunately only this won’t do the trick in IE (big surprise :D) and it will require another small hack. You have to set the text-align property for the BODY to center and then redo it for the DIV.

One last thing: in Mozilla, when resizing the window, a part of the DIV will fall on the left of the page, making the page unusable. Simply specify a min-width for the BODY.

If you take into account that you can replace BODY with any other DIV, then you have a general DIV centering method in just a few lines of CSS code.

Categories: Web Tags: , , ,
  1. arun
    February 6, 2008 at 8:30 am

    How to vertically align the contents of a div in center

  2. March 20, 2009 at 9:18 pm

    nice tip – thanks

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: