Monthly Archives: September 2010

Adding | Separators Between Vertical Menu Items Using CSS

1
Filed under Uncategorized

The content and design of a web page should be coded separately. Content should be in HTML and design in CSS.

That’s why I cringed when I saw the code for this navigation menu:

Home|About|Around

<a href="#">Home</a><span class="separator">|</span><a href="#">About</a><span>|</span><a href="#">Around</a>

.separator {
margin-left: 3px;
margin-right: 3px;
}

Not only are the separators coded in HTML, but the spacing around them are in CSS. So without CSS, the content looks like this:

Home|About|Around

That’s not very search engine or screen reader-friendly.

So what needs to be changed?

  • The links should be coded as an HTML list. This is standard for navigation menus.
  • The separators should be coded in CSS since they are only useful for visually separating the links.
  • And, just to make things hard, the new menu should appear exactly as the old one.

First, we must put the items in a list.

<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Around</a></li>
</ul>

Now, that’s a menu! But it doesn’t look anything like the original. Let’s line those links up vertically.

li {
display: inline-block;
}

Now for the fun part: adding the separators.

li:before {
content: " | ";
}
/* But we don't want the separator before the first item! */
li:first-child:before {
content: none;
}

Brilliant, eh? It looks just like the original menu, but is now coded well.