Web Tutorials: Centering Images
In a previous part of this tutorial, I talked about using CSS to center text with the text-align:center attribute. This article picks up where that one left off and talks about centering images.
Centering Images with CSS
We can't use the text-align attribute to center images with CSS because images are treated differently than text.
That's the bad news. The good news is that centering an image isn't all that difficult and only requires a bit of CSS coding.
To center an image using an inline style definition, you simply need to set the margins to auto and add the display:block definition that will cause the browser to use the entire width of the space regardless of the size of the image.
<img src="centeredpicture.jpg" style="display: block; margin-left: auto; margin-right: auto">

To center an image using a style definition, you would need to create a style definition and to define which style to use with your image.
The sample code below is a simple webpage that only displays a single centered image. It defines the style definition in the head section as well as shows how to direct the image to be displayed using that style definition.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<style type="text/css">
<!--
.midway {display: block; margin-left: auto; margin-right: auto}
-->
</style>
</head>
<body>
<img src="centeredpicture.jpg" class="midway">
</body>
</html>
Do not use center or middle for the name of your style as they both have specific uses within HTML and CSS and are referred to as reserved words.
Vertical Centering
It would seem logical that setting the top and bottom margins to auto would work to center an image vertically but the functionality simply does not exist.
There has been some suggestion that it may be included in the next version of the W3C standard but for now you would have to use tables to center something vertically.
The suggestion to use display: table-cell from the www.W3.org website does not work across all browsers and is more of a theoretical solution than a practical one.
Centering with CSS
Be sure to check out our other two tutorials in this series - Centering Text with text-align and Centering Text with Auto Margins.
HelpForWebBeginners.com is a website dedicated to providing free, easy to understand, online How To's for true web beginners. While the materials are not free or available for reprints, they are offered freely for individual use. Please use the contact page to let Michele know if this tutorial has been helpful or if there are any other beginner web programming or MySpace related tutorials you would like to see.