Centering an image or an element on a web page

The 50% Solution



The problem:

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

The 50% Solution

Using position: absolute; 50% Percent and subtract 1/2 (50%) of the width and height of the image

How?
Make the Box and the image have the property and value position: absolute; set the Top, Right, Bottom and Left positions to 50% and subtract from margin-top, margin-right, margin-bottom and margin-left 1/2 (50%) of the width and height of the image in pixel units.



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

The source

				
<style type="text/css">
 

body {text-align: center;}
#largebox {
text-align: left;
	width:500px;
	height:400px;
	background-color:#CFF;
	border:dotted #000000 1px  ;
	position:absolute;

/* Apply the 50% rule */

left: 50%;
	top: 50%;
	right:50%;
	bottom:50%;

/*Subtract 50% (1/2) the width and height of the image or element

the minus sigh  moves the element to the left */ 
	margin-left: -250px;
	margin-top: -200px;
	margin-right: -250px;
	margin-bottom:-200px;

}
#smallimage {
	background-color:#F00;
	border:solid #000000 2px ;
	position:absolute;
	left: 50%;
	top: 50%;
	right:50%;
	bottom:50%;
	margin-left: -100px;
	margin-top: -66px;
	margin-right: -100px;
	margin-bottom:-66px;

}

</style>
</head>

<body>

<h2>Method 2: The 50% Solution</h2><h3></h3> Using Absolute, 50% Percent and subtract 1/2 (50%) of the width and height of the image</h3>
<p style="text-align:left; text-indent:5em;">Make the Box and the image have the property and value position: absolute; set the Top, Right, Bottom and Left positions to 50% and subtract from margin-top, margin-right, margin-bottom and margin-left 1/2 (50%) of the width and height of the image in pixel units. 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>