When I first started playing with HTML, the way you centered your HTML elements was to place a <center> tag around them. If you try using a <center> tag in your HTML in any type of IDE, you’ll get a deprecation warning. (If you’re new to programming, deprecation means that the functionality is slated to be phased out.)
So, what do you do instead? Well, there are two instances in which I was wishing I knew how to get the same effects I got from <center>: centering text and centering elements.
Centering Text
Centering text is relatively easy. In your stylesheet, you use the ‘text-align’ style element. Here’s an example.
1 2 3 | <div style="text-align: center;"> This is centered text. </div> |
Here’s the code in action:
You can also do on a class or id in your css files as well.
Centering Elements
To center elements is a little trickier. The trick is to set your right and left margins to auto. Here’s an example from a css file:
1 2 3 4 5 6 7 8 | body { text-align: center; } .wrapper { width: 900px; margin: 0 auto; text-align: left; } |
This is how this page is centered. The div containing the entire content of the page has right and left margins that are set automatically.







4 Comments »
Richard@Home
July 29, 2009
Good tip, but doesn’t work cross browser I’m afraid. You need to do the following:
body {
text-align: center;
}
.wrapper {
width: 900px;
margin: 0 auto;
text-align: left;
}
Hope this helps :-)
Chuck
July 30, 2009
I can’t believe I missed that! Thanks for pointing it out. I’ll fix it in the post.
Adrian von Gegerfelt
August 2, 2009
You shouldn’t encourage people to use the style attribute because it has the highest rank of CSS definitions and is really hard to overwrite with a stylesheet.
Brandon Buttars
February 2, 2010
Agreed with Adrian. Whenever possible, assign a class and style it by it’s class. I will sometimes create a .center class and then I can use it, but I try and assign ID’s to most layout elements when possible.
.center {text-align:center}
Leave a comment