CSS: Replacing the
tag

by woody2shoes on July 29, 2009

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.

This is centered text.

Here’s the code in action:

This is centered text.

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:

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.

  • http://richardathome.com Richard@Home

    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 :-)

    • http://charlesmaxwood.com Chuck

      I can’t believe I missed that! Thanks for pointing it out. I’ll fix it in the post.

  • http://www.thinkadrian.com Adrian von Gegerfelt

    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.

  • http://brandonbuttars.com Brandon Buttars

    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}

Previous post:

Next post: