Real World Style

css layouts, tips, tricks, and techniques

Giraffe peeking over the image...

« Still alive | Main | New Article at Digital Web Magazine »

August 04, 2004

Centered links

I recently received an email asking if I knew how to center a box of links on a page like what is seen on this example page: http://www.thomasjanotta.de/blulink1.php

While the question was really about centering the box, I thought I’d also take a stab at getting rid of the table that was being used to create and house the links.

Centering the box

The centering part is rather simple. Since the box has a width, you just need to give the left and right margins a value of auto. The CSS for the DL looks like this:

dl#links {
    font: 12px/16px verdana, arial, helvetica,
          sans-serif;
    width: 230px;
    margin: 2em auto; /* This is what centers the
                         box the first value is for
                         the top and bottom margin
                         the second value (auto)
                         splits the difference between
                         the right and left margins */
}

This works in the latest versions of the most popular browsers. Some older browsers will not center the box. There are some workarounds, but I’ll leave it as an exercise for the reader who wants to support those browsers

Recreating the links

It is probably no surprise that I chose to use a list to mark up the links. In fact I decided to use a definition list since each link has two parts, the link and the number of hits the link has. So the link became the DT and the number of hits the DD.

Having decided that, it was a just matter of replacing the TABLE markup with a DL. Due to the way the original was marked up it was a relatively simple search and replace process to accomplish this, even allowing for the extra class on every other link to get the gray background.

The CSS is pretty straightforward, too. I adapted the technique in my 7-10 Split article, applying the rules to the DT and DD rather than extra SPANs and DIVs. And once CSS 3 is supported by enough browsers, we’ll be able to do away with the extra class on every other line, too.

Here is the finished centered box o’ links via CSS (View source to see the CSS).

Posted by Mark on August 4, 2004 10:09 AM