Box Centers in Internet Explorer Only

Why does the following code show a centered box only in Internet Explorer, but not in Chrome, Opera, or Firefox?

<!doctype html>
<html lang=“en”>
<head>
<title>Test of Centered Image</title>
<meta http-equiv=“Content-Type” content=“text/html; charset=utf-8” />

<style type=“text/css”>
#redblock {
position: relative;
background-color: red;
width: 1000px;
height: 637px;
padding: 0;
border: double #000000 8px;
}
.centeredImage {
text-align:center;
margin-top:0px;
margin-bottom:0px;
padding:0px;
}
</style>
</head>
<body>*
<div class=“centeredImage”><div id=“redblock”>This is the red block.</div></div>
<p>The red block is positioned 200 pixels from the top and 200 pixels from the left.</p>
</body>
</html>

text-align : center only centres the text inside the element - it doesn’t centre the element itself. To centre a div you need to use margins: o auto and also give it a width that is less than the width of its container.

Probably because IE is misbehaving. You didn’t mention which version of IE, but it doesn’t really matter. This code shouldn’t center the redbox.

You can add {margin:0 auto} or {display:inline-block;vertical-align:top;} to #redblock and the box will center.

I do not understand the sentence in the paragraph. There is nothing in the code to position the image 200px from the top of the page nor 200px from the left edge of the window.

Hope this helps a little.

Hi,

In IE7 and under (and any version of IE9 and under when in quirks mode) text-align:center will center child block elements. This is not so much a bug as such but more the way the browser was designed and follows a behaviour created in ie5 which didn’t understand margin:auto should be used to center elements (and incidentally where inline elements can also have dimensions although they shouldn’t do so as it is against the specs).

The correct way to center block elements is to use margin:auto but the element will need a width of course.