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:
- Put everything that needs to be centered in a div tag and give it an unique id.
- 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.
- 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. - 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.
Marco posted this response on December 11th, 2003 at 8:27 pm
Welcome back!!!
Benjamin posted this response on December 11th, 2003 at 8:35 pm
Thx Marco
Iva posted this response on December 15th, 2003 at 1:02 am
This is pretty helpful. Thanks:)
Benjamin posted this response on December 15th, 2003 at 12:09 pm
Thx Iva