Centering With CSS

This was one of the things that bothered me so much when I was first learning CSS. How in the world do you properly center things without using the outdated <center> tag? Well the answer is simple. And all it requires is some creative margin work and some easy to remember text-align’ing.

To center an entire layout with CSS you would add the following to your style sheet:

body { text-align: center; }

This tells the browser that anything between the <body> tags should be centered. This is often the easiest way to center a web layout. However this is one thing to keep in mind with this method. Because you’ve set the text-align to center, it will center all text underneath <body>. To change that, simply add

{ text-align: left; }

to your div#content, or div#sidebar or wherever you need the text to be aligned to the left like normal.

There is one other method for centering elements that doesn’t work in all browsers (which is why combining the two methods is often the best way). This following method isn’t to complicated, all you have to do to center the element you wish centered is add the following to your style sheet:

div#wrapper { margin: 0 auto; }

This tells the browser that the top and bottom margins should be 0, and that the left and right margins should be equal. This translates into the element being centered. If you combine these two methods you can be sure that your CSS is properly centering things.

As always keep in mind that IE handles things slightly differently. And while it doesn’t handle the margin auto trick, it does center things with the text-align trick. You could always play around with margins to get the positioning you want down just perfect. My next posting will include some ways to vertically align a design without all the extra fluff. Which is something that, sometimes, can be quite difficult. Especially when you take into account IE and the other quirky way browsers act.

Post a Comment

Your email is never shared. Required fields are marked *

*
*