Tutorial: Centering a div

by Tim Gallant

Once again, very simple - same idea as the table. Here is the CSS for the gray div that you are looking at:

#centered {
margin: auto;
width: 700px;
background-color: #E2E3E7;
border: 1px solid #B8BAC5;
padding: 11px;
}

And in your HTML:

<div id="centered">

Easy, isn't it?

And, once again, to make sure that Internet Explorer 5 plays nicely:

body {
text-align: center;
}

And, because that has centered the text, you will now need to apply left-align to your table text. So:

#centered {
margin: auto;
width: 700px;
background-color: #E2E3E7;
border: 1px solid #B8BAC5;
padding: 11px;
text-align: left;
}

This is a fixed-width example. Once again, see Part 2 to look at a fluid model.

Now, chances are that if you are centering an item on a page, you might want to use it to "wrap" all of your page content, so that the whole page looks centered. If you are using absolutely-positioned elements inside your "wrapper," you will need to do one more thing to the wrapper: set it to position: relative; in your CSS. Otherwise, your absolutely-positioned elements will be positioned relative to the body of the page, rather than to your "wrapper" - no matter where they appear in your HTML code. Thus, the above code would now look like this:

#centered {
position: relative;
margin: auto;
width: 700px;
background-color: #E2E3E7;
border: 1px solid #B8BAC5;
padding: 11px;
text-align: left;
}

One more thing: if you are using a wrapper, make sure you understand the "box model."

Return to main tutorials page.

Tutorial by Tim Gallant of Pactumgroup © 2005