J.D.
Dec 30th 2004, 2:32 am
Anybody who tried to use the proper CSS way to center a block element (e.g. div, table, etc) in IE, knows - it's pain. As it turns out IE is capable to do the right thing. Here's how. Enjoy.
If you need to center a block level element like this:
<div style="width: 60%;">some text</div>
, the CSS way is to make left/right margins auto. For example:
<div style="width: 60%; margin: 1em auto;">some text</div>
Unlike FireFox and Opera, IE by default ignores this rule and renders the div left-aligned. If you use any centering tricks, like this one:
<div style="text-align: center;">
<div style="width: 60%;">some text</div>
</div>
, the inner div will be centered, but so will be the text inside (text-align is inheritable).
A simple fix that makes IE follow the pack is to add the full DOCTYPE declaration to the document. For example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
...
The DTD reference must be included in DOCTYPE for this to work. That's all - no more browser-specific centering. Here's the full test for those who was patient enough to read to this point and want to give it a try:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>...</title>
</head>
<body>
<div style="width: 60%; border: 1px solid red; margin: 1em auto;">some text</div>
</body>
</html>
J.D.
If you need to center a block level element like this:
<div style="width: 60%;">some text</div>
, the CSS way is to make left/right margins auto. For example:
<div style="width: 60%; margin: 1em auto;">some text</div>
Unlike FireFox and Opera, IE by default ignores this rule and renders the div left-aligned. If you use any centering tricks, like this one:
<div style="text-align: center;">
<div style="width: 60%;">some text</div>
</div>
, the inner div will be centered, but so will be the text inside (text-align is inheritable).
A simple fix that makes IE follow the pack is to add the full DOCTYPE declaration to the document. For example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
...
The DTD reference must be included in DOCTYPE for this to work. That's all - no more browser-specific centering. Here's the full test for those who was patient enough to read to this point and want to give it a try:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>...</title>
</head>
<body>
<div style="width: 60%; border: 1px solid red; margin: 1em auto;">some text</div>
</body>
</html>
J.D.