Create a CSS navigation bar showing the current state

These days it’s almost a standard to use an un-ordered list element for your page navigation. While a vertical list in some sidebar is some easy piece of work, is the horizontal CSS navigation bar a little bit more complicated.

Preview and example navigation

We need to float the list elements to get them in the horizontal order. There are many great examples on this CSS resource site and also our example here is based on one of the tutorials listed on the suggested site. Notice the active state in the preview above, this is not easy without any scripting language.

Generating the HTML snippet

The next snippet has for the first list item the attribute id “current”. To create some intelligent function to have one code snippet for all of our pages we need some tiny PHP function to get some dynamic navigation:

First we create an array for the links and link labels we want to use in our navigation. You can use also some database result, but you need to change the code a little bit (using a while loop in place of a foreach). Next we loop through all array elements (or the result set) and test every link value against the current URL. If there is a match we add the ID attribute the code. At the end we return the whole HTML snippet.

Some CSS style for our navigation

While the navigation is very simple (just using one level) we need only some style sheet for the unordered list elements. We need to disable the list-style-type and we float the list nodes inside the unordered list container.

Don’t forget that we are working with a block type element and all those elements are having a 100% width by default. While using a float we change that behavior and the list nodes are ordered in a horizontal direction. Next we like to have some more design elements and also a different style if we hover the mouse above a link item. We add some other style definition for the link/hover elements. At last but not least we need some extra style for the current state in our navigation bar:

You can use this PHP/HTML code example for all your navigation menus, just use different style sheets. If you need more ideas just check the CSS resource site link at the begin from this tutorial.

Comment Rules

Don’t post your code here, post your code block or snippet to pastebin and include the pastebin URL in your comment.

I delete all comments with non related links inside the comment text. Don't use keywords for the field of your real name (most people like to use your name for their answer). Keep your comment related to the topic, if your question is off-topic, please use the contact form instead.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website