Centering an image or an element on a web page

The display block Solution

The problem:

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

The Display Block Solution

Tricky... The key to centering an image on a web page is that by default an image is an inline element.

"Inline Elements always begin on the same line. Height, line-height and top and bottom margins can’t be changed. Width is as long as the text/image and can’t be manipulated!"

Unless you change the image to act like a block element using the Property and Value display:block;

You could put the image in a div, but why add a div when you don't need it?



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;
text-indent: 5em;
margin: 0 }

#largebox {
text-align: left;
	width:500px;
	height:400px;
	background-color:#999288;
	border:dotted #000000 1px;
	margin: 0 auto;
			
}


#smallimage {background-color:#F00;
background-color:#CFF;
	border:solid #fff 4px;
	display: block;
	margin: 120px auto ;

}


</style>
</head>

<body>
<!--
<h2>Centering an image using display: block;</h2>
<p style="text-align:left;">Tricky... The key to centering an image on a web page is that by default an image is an inline element. </p>
<blockquote style="text-align:left;"> <em><strong>"Inline Elements always begin on the same line. Height, line-height and top and bottom margins can’t be changed. Width is as long as the text/image and can’t be manipulated!"</strong></em></blockquote>
<p style="text-align:left;">Unless you change the image to act like a block element using the Property and Value <em><strong>display:block;</strong></em></p><p style="text-align:left;">You could put the image in a div, but why add a div when you don't need it?</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>