Useful CSS for Navigation Bars

Share

15th April 2010

Useful CSS for Navigation Bars

We're working on lots of sites at the moment, and one theme that is regularly reappearing is the need to style up navigation bars with dividers between each hyperlink element.

With CSS this is easy to do - simply set the left border of the A tag to

#navigationBar a { border-left:1px solid #red; }

Link dividers using css - showing the extra left divider on the first element

However this means that the first link in the navigation bar will have a divider to its left usually next to the page margin. This looks weird. So to get around this we use the "first-child" selector to set a different style for the first of the hyperlinks, like so:

#navigationBar a { border-left: 1px solid red; }
#navigationBar a:first-child { border-left: 0; }

The links again with the left divider removedThis removes the border from the first A tag in the navigation bar, and Bob's your uncle.

The other regular requirement is to have the hyperlink styled to act like a button, with not just the letters acting as the link, but the space around the letters too.

We achieve this by making the hyperlinks into floated block elements, and then setting the padding and line-height to vertically and horizontally spread the effect of the link. Then attaching a coloured background or image to the new link makes it appear as a button when you hover over it.

#navigationBar a { display:block; float: left; line-height: 20px; padding: 5px 15px; background-color: navy; color: white; }
#navigationBar a:hover { background-color: silver; color: navy; }

And this is the sort of result, showing the whole link highlighted in silver when the cursor hovers over it:

Navigation button links in CSS

Other News