Sunday, June 04, 2006

Easy CSS Delimited lists

Any easy menuing system in CSS. As a list of links, a menu should rightly be included in an HTML list.

What we need is a simple way to display <li> elements as a flat, delimited list. Take, for exampe, the simple menu at the top of this page. It consists of a simple <ul> list:

<ul class="menulink">
  <li>home</li>
  <li><a href="/pb/port/">portfolio</a></li>
  <li><a href="/pb/contact.html">contact me</a></li>
</ul>

First, we turn off the dots before our list item and remove the indentation. Remember that Firefox and Safari use the padding space to specify the space for the dots, but most other browsers use the margin space for this. Unfortunately, CSS specifications don't exactly say which it should be. So to cover our bases, we're going to zero out both the margin and the padding:

ul.menulink {
  list-style: none;
  margin: 0;
  padding: 0;
}

Next, we flatten it into a line with:

ul.menulink li {
  display: inline;
}

Now we add our delimiters by using the pseudo-selector :after (and give it some space to breath):

.menulink li:after {
  margin-left: 3px;
  margin-right: 3px;
  content: "|";
}

That adds our vertical bar after each item. But what about the last one? We don't need it, so let's remove it with:

.menulink li:last-child:after {
  content: "";
}

The key to understand this is to remember that the :last-child pseudo-selector refers to the last element of it's own kind (i.e., the last <li> tag).

This is great CSS, but Internet Explorer 6 doesn't recognize these pseudeo-selectors.