Centering a webpage using
CSS and auto-width margins

Centering a webpage using CSS is simple process using the auto-width value against the margins property. The basic idea is you create a container with a fixed width and then set the left and right margins on that container to auto (more information from the W3C).

The Code

body {
	margin:20px 0px;
	padding:0px;}
	
#container {
	width:600px;
	margin:0px auto;
	padding:10px;
	border:2px solid #5a9301;
	background-color:#eee;}

How to use

  1. Wrap the entire web page, between the BODY tag, inside of a DIV container
    <body>
    	<div id="container">
    		--all your content--
    	</div>
    </body>
    
  2. Copy the code from above into your style sheet and set the width of the container to suit (typical is 760px for a 800px wide site)
  3. Make sure your page has a DOCTYPE of at least XHTML 1.0 Transitional
  4. Test the page

From the W3C

The horizontal position and size of a non-floating, block-level element is determined by seven properties: 'margin-left', 'border-left', 'padding-left', 'width', 'padding-right', 'border-right' and 'margin-right'. The sum of these seven is always equal to the 'width' of the parent element.

Three of the seven properties can be set to 'auto': 'margin-left', 'width' and 'margin-right'. For replaced elements, a value of 'auto' on 'width' is replaced by the intrinsic width, so for them there can only be two 'auto' values.

If exactly one of 'margin-left', 'width' or 'margin-right' is 'auto', the UA will assign that property a value that will make the sum of the seven equal to the parent's width.

If none of the properties are 'auto', the value of 'margin-right' will be assigned 'auto'.

If more than one of the three is 'auto', and one of them is 'width', then the others ('margin-left' and/or 'margin-right') will be set to zero and 'width' will get the value needed to make the sum of the seven equal to the parent's width.

Otherwise, if both 'margin-left' and 'margin-right' are 'auto', they will be set to equal values. This will center the element inside its parent.

If 'auto' is set as the value for one of the seven properties in an element that is inline or floating, it will be treated as if it were set to zero.