Centering an image or an element on a web page

The Absolute, Zero and Auto Solution



The problem:

You want to place a "box" and an image on a web page. AND, you want them centered.

The Absolute, Zero and Auto Solution

Make the Box and the image have the property and value position: absolute; and Use Margin: auto; but set the Top, Right, Bottom and Left positions to 0 (zero). Check out the source below!



Check out the embedded source below! And Check to see if this works in all browsers!

The source

				
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">

body {text-align: center;
margin: 0 auto;
}

#largebox {
text-align: left;
	width:500px;
	height:400px;
	background-color:#407751;
	border:dotted #000000 1px  ;
	position: absolute;
	margin: auto;
	left:0; right:0;
	top:0; bottom:0;

		
}
#smallimage {
	background-color:#F00;
	border:solid #fff 2px ;
	position: absolute;
	margin: auto;
	left:0; right:0;
	top:0; bottom:0;
	

	}


</style>
</head>

<body>
<!--
<h2>Method 1: Absolute, Auto and 0 (zero)</h2>
<p style="text-align:left; text-indent:5em;">Make the Box and the image have the property and value position: absolute; and Use Margin: auto; but set the Top, Right, Bottom and Left positions to 0 (zero). Check out the embedded source!
</p>
<p>Check to see if this works in all browsers!</p>
-->
<div id="largebox">
 <img src="../imageproc/thumbsize/200pixels.jpg" alt="A thumbnail 200 pixels wide of MoultonFalls Moss" width="200" height="133" id="smallimage" />
</div>

</body>
</html>