Centering content, without tables

Switching from table design to a table-less design, isn’t always that simple. Ok you got your positioning right, all your fonts are now in your CSS file, but what about your centered design, where the content has a fixed width (let’s say 700 pixels).

The <center> tag is depreciated and the CSS property text-align: center; only works for text not entire blocks. You could of course set a fixed margin to get it of the left side, but it still isn’t centered.

Here is a better option:

  1. Put everything that needs to be centered in a div tag and give it an unique id.
  2. Now give div your fixed width (700px in our example) and set the left and right margin to auto.

Your HTML should look like this now:

<div id="centereddiv">This entire block should be 700 pixels wide and centered.</div>

And your CSS should look something like this:

#centereddiv {
	width: 700px;
	margin-right: auto;
	margin-left: auto;
	background-color: #CCC;
}

First of all, you might wonder what the background color property is doing there. Well, it is only to show you the result better.
If you try this, it will work in all browsers but IE.

If you want it to work in IE too, which you probably should, since most people use it, you need to add a few things into your css.

  1. Define text-align: center; to the parent tag of the tag that needs to be centered. So if your div is directly under your body tag, define it in the body tag.
  2. Define text-align: left; or right/justify, however your text needs to be aligned.

Your CSS will look like this:

body {
	text-align: center;
}
#centereddiv {
	text-align: left;
	width: 700px;
	margin-right: auto;
	margin-left: auto;
	background-color: #CCC;
}

Now your code also works in IE. That’s all there is to it, and with less code than when you use tables.

4 Responses to “Centering content, without tables”.

  1. Welcome back!!!

  2. Thx Marco

  3. This is pretty helpful. Thanks:)

  4. Thx Iva

Comments are closed.