Centered Horizontal Menu

I was recently working on a website design and was trying to get each menu link to be separated by a vertical line. I wanted this to be dynamic as menu items would be added automatically trough the content management system so i wanted to avoid hard coding borders or pipe ( | ) between between the links. the main difficulty i was having was to remove the vertical line on the start of the menu or end depending on whether I used left borders or right borders. After researching the w3c CSS documentation and some web searches I found a dynamic solution that achieved the layout I was aiming for.
The best method I found that would easily fit in with the web site's design was to use the :first-child Pseudo CSS selector. This allowed me to apply a style, in this case a left border to each child of a container tag.
Here is the HTML code:

  1. <div id="nav">
  2. <ul id="nav-list">
  3. <li class="menu-item"><a href="#">Home</a></li>
  4. <li class="menu-item"><a href="#">About</a></li>
  5. <li class="menu-item"><a href="#">Contact</a></li>
  6. </ul>
  7. </div>

And The CSS:

  1. #nav{
  2. margin: 0;
  3. padding: 0;
  4. text-align:center;
  5. font-size:1.3em;
  6. }
  8. #nav ul#nav-list{
  9. clear: both;
  10. list-style-type: none;
  11. margin: 0;
  12. padding: 0;
  13. display:inline-block;
  14. text-align:center;
  15. }
  17. #nav ul#nav-list li{
  18. float: none;
  19. margin: 0;
  20. padding: 0;
  21. display:inline-block;
  22. border-left:1px solid #000;
  23. text-align:center;
  24. }
  26. #nav ul#nav-list li:first-child{
  27. border:none;
  28. }
  29. #nav ul#nav-list li a{
  30. color:#000;
  31. text-decoration:none;
  32. padding: 0 2em 0 2em;
  33. }

For me the key in this solution is on line 26 of the CSS which removes all borders from the first list item.
Centered horizontal menu example

Add new comment

By submitting this form, you accept the Mollom privacy policy.