Centering objects with CSS

There are four ways to center things using CSS:
centering text
centering a block
centering an image

Centering Text with CSS
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 horizontally inside the parent element, or the width of the paragraph if that is set.

<p>This text is centered.</p>

Some things to remember when centering text with the text-align property:

Text that is centered with the text-align property will be centered within whatever element contains it (the parent element).
This is an alignment of the text, like left alignment, right alignment, and justified alignment. It doesn’t move the entire block of text to the center.

Centering Blocks of Content with CSS
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”. Here is the CSS:

div.center {   margin-left: auto;   margin-right: auto;   width: 8em; }
And this is the HTML that applies to:

<div>This entire block is centered, but the text inside it is left aligned.</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 with CSS
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 should explicitly tell the browser that the image is a block element. Then you can center it as you would a block. Here is the CSS:

img.center {   display: block;   margin-left: auto;   margin-right: auto; }

Resource: http://webdesign.about.com/od/beginningcss/a/aa012207.htm


One response to “Centering objects with CSS”

  1. admin says:

    This method has worked most of the time, but beware it does not work for me all of the time. If someone knows of a foul proof way to center these elements above please share. This is not including deprecated tags like

    .

    Thanks alot

Leave a Reply

Your email address will not be published. Required fields are marked *