There are four ways to center:
- centering text
- centering a block
- centering an image
- vertically centering a block or image
Centering Text
The easiest thing to center is text. There is only one style property you need to know to center text:
p.center { text-align: center; }
Any paragraph written with the "center" class will be centered vertically on the page.
<p class="center">This text is centered.</p>
Text that is centered with the text-align property will be centered within whatever element contains it.
Centering Blocks
Blocks can be any type of block that has a defined width. The proper way to to this with CSS is to set both the left and right margins to "auto".
div.center {
margin-left: auto;
margin-right: auto;
width: 8em;
}
<div class="center">This block is centered also.</div>
As long as your block has a set width, it will center itself inside the containing element. But any text that is contained in the block will not be centered.
Centering Images
Images are a little trickier. While most browsers will display images centered using the same text-align property, it's not a good idea to rely on that technique, as it is not recommended by the W3C. Instead, you need to explicitly tell the browser that the image is a block element. Then you can center it like you would a block.
img.center {
display: block;
margin-left: auto;
margin-right: auto;
}
<img src="blwebcam-sample.jpg" alt="Suni" class="center" />
Vertically Centering Images and Blocks
CSS 2 doesn't have explicit support for centering items vertically on the page. There is a way to trick some browsers into displaying the contents vertically centered, but it doesn't work well in IE 7 and not at all in IE 6. This is how the W3C recommends you center text vertically until CSS 3 support is available.
- Place the elements to be centered inside a containing element, such as a DIV.
- Set a minimum height on the containing element.
- Declare that that containing element is a table cell.
- Set the vertical alignment to "middle".
.vcenter {
min-height: 12em;
display: table-cell;
vertical-align: middle;
}
<div class="vcenter">
<p>This text is vertically centered in the box.</p>
</div>
In the meantime, you can use margins and padding to get some effect of centering in IE, but it won't be 100%.
There are some ways to force IE to center and then use conditional comments so that only IE sees the styles. But they are ugly. I'd rather just wait for real vertical centering to be supported in the browser.
Center Your Entire Page
Centering the entire contents of your Web page depends upon whether you're using a fixed width layout or a liquid layout.
Center a Document with a Fixed Width Layout
Center a Document with a Liquid Layout

