CSS Centering – fun for all!

How do you center a containing block on a page using CSS? There are two main methods and the choice should be made based on whether your page layout is liquid (will move in and out depending on the size of the browser window) or fixed width.

Centering liquid layouts

Liquid layouts are easy to center using margins on each side of the containing box. The margins can be set with em, pixel or percentage units.

.container
{
	margin-left: 10%;
	margin-right: 10%;
}

Centering fixed-width layouts

Theoretically, you should be able to apply auto margins to the left and right of the containing block and it should center on the page.

The W3C Visual formatting model states: “If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”

So, a containing block should be able to be centered using the following rules:

.container
{
	margin-left: auto;
	margin-right: auto;
	width: 50em;
}

Or, a shorthand version using the margin property:

.container
{
	margin: 0 auto;
	width: 50em;
}

Problems

Some browsers do not center the containing blocks using this method as they ignore the auto margins. These browsers include:

  • NN4 (Mac and Win)
  • Win/IE4
  • Win/IE5
  • Win/IE5.5
  • Win/IE6 (when in quirks-mode)

By adding two simple rules, this problem can be overcome in all of the browsers mentioned above, excluding NN4.

1. Center the body

While these browsers ignore auto margins, they will follow “text-align: center”. If this is applied to the body, the containing block will center correctly. So, a new rule is added:

body
{
	text-align: center;
}

.container
{
	margin-left: auto;
	margin-right: auto;
	width: 50em;
}

2. Resetting text-align

The only problem with this new rule is that all content on the page is now center-aligned. To overcome the center alignment problem, a new declaration is added within the containing block rule set – “text-align: left”. The final CSS code is:

body
{
	text-align: center;
}

.container
{
	margin-left: auto;
	margin-right: auto;
	width: 50em;
	text-align: left;
}

Forcing scroll bars

Update: 17 October 2010: Centering the container in the browser window can sometimes cause problems when moving from long pages to short pages. Long pages may have vertical scroll bars while short pages may not. This can be fixed by adding the following rule – which will add a vertical scroll bar to all pages regardless of their length.

html { overflow-y: scroll; }

Translations