April 26, 2005 6:59 pm

The Very Belated Tip of the Week

:note: The Scissor Sisters – “Better Luck”

I am so crap at doing these on time.

How to Properly Center Align

So you’ve got an element you want to center. It could be an image, it could be a div, a span, whatever. You want it centered. Do you use the antiquated <center> tag in HTML? NO! And I’ll tell you why.

It is because the <center> tag is being deprecated. What does that mean? I’ll tell you.

dep�re�cate (dep’ri-kat’):
To make invalid or obsolete by removing or flagging the item. When commands or statements in a language are planned for deletion in future releases of the compiler or rendering engine, they are said to be deprecated. Programmers should begin to remove them from the source code in subsequent revisions of their programs.

That is an awesome definition of deprecation, and it explains why you shouldn’t continue to use the <center> tag even though browsers still support it. Because eventually (and yes, this is probably ages away still) the <center> tag won’t work.

So how to do it properly? you might ask. It’s simple, and all it involves is a bit of CSS. I’ll start with the quick and dirty way first.

Inside the tag of the thing you’re trying to center, add a style attribute-value pair that sets the left and right margins of the element to auto. For instance, on a div:

<div style="margin-left: auto; margin-right: auto;">

or on an image:

<img src="blah.gif" alt="blah" style="margin-left: auto; margin-right: auto;" />

You get the idea. The “better” way to do this is to set a class in your CSS file that looks something like this:

.centerthis
{
margin-left: auto;
margin-right: auto;
}

…and then anything you want to be centered, just add a class="centerthis" to the tag.

It’s terribly easy. Have fun centering things!

File Under: ,

Tagged: No tags

Comments are closed here.