Menu Separators 101

Menu separators are widely used in our daily web-development process, and it would be great if we can simply implement these basic visual elements by CSS without introducing more redundent HTML/CSS markups.

To start with, let's say we have a 4x4 image separator for our separator, then we will use this image as background for our example of HTML list.

CSS / HTML

<style> ul{ margin:0; padding:0; list-style-type:none; border:dotted 1px #B7B7B7; /*self-clearing for CSS float*/ overflow:hidden; zoom:1; } li{ background:url(http://us.i1.yimg.com/us.yimg.com/i/us/fd/gr/ui/dtyl.gif) 0 0 repeat-y; padding:6px 12px; float:left; } </style> <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> </ul>

As you can see, the separators are displayed as background images for each list item, and we need to remove the background image of the first list item to make the list look nicer.

You probably knows that there're many ways to make this happen, such as adding extra class name to the first list item :

<style> li.first{ background-image:none; } </style> <ul> <li class="first">item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> </ul> Or using CSS pseudo selector : <style> li:first-child{ background-image:none; } </style>

However, these solution would require extra class names, or IE-6 incompatible CSS selectors, and we may want to avoid that.

Inspired by the Blog posted by Duan Zheng Chun, he introduced a very simple but compatible and elegant CSS solution to display separators by CSS with negative margins.

Since he original post was written in Chinese, I thought that I may take over his example codes and modified them a little bit and would like to share it with the public in english.

So let's start with the example

ul{ overflow:hidden; list-style-type:none; border:dotted 1px #B7B7B7; zoom:1; margin:0; padding:0; } ul li{ display:block; float:left; background:url(http://us.i1.yimg.com/us.yimg.com/i/us/fd/gr/ui/dtyl.gif) 0 0 repeat-y; margin:0 4px 0 -4px; /*use negative margin-left to hide the background image*/ padding:6px 12px 6px 12px; zoom:1; }

Make sure that we add overflow:hidden; to the <UL /> element, not only we can clear the CSS floats of its child lits items , but also crop the negative margin-left for the first list item.

<style> ul{ overflow:hidden; } </style>

Similarly, we can do this for the vertical menu

<style> ul{ overflow:hidden; list-style-type:none; border:dotted 1px #B7B7B7; zoom:1; margin:0; padding:0; } li{ display:block; background:url(http://us.i1.yimg.com/us.yimg.com/i/us/fd/gr/ui/dtyl.gif) 0 0 repeat-x; margin:-4px 0 4px 0; line-height:normal; padding:10px 12px 6px 12px; zoom:1; } </style> <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> </ul>

That's it, isn't it?

Hedger Wang