In this second part of a two-part series on cascading style sheets you will learn an alternate method to create dynamic navigation bars with the help of a little HTML and the jQuery animate method.



If you think that you already knew all about the “background-position” CSS property, or that its functionality was limited to statically positioning background images within web page elements, you should check out this tutorial. In an approachable fashion, you’ll learn how to construct an animated navigation bar by using the property in question along with a few straighforward jQuery methods. 

In the first installment of this two-parter (CSS Animated Navbars), I developed an introductory example, which demonstrated how to couple the “background-position” property to jQuery’s "animate()” method, in order to build up our navigation bar. Thanks to the versatility offered by the pertaining method, it was really easy to vertically animate the bar’s buttons, creating an eye-catching mouse over effect, quite different from the ones that can be implemented with plain CSS.

Being the library’s workhorse - at least when it comes to animating different properties of an HTML element - the “animate()”method can be used in all sorts of clever ways. In this final episode of our two-part tutorial I’ll be showing you another approachble example - how to use the method, but this time for horizontally animating the elements of the earlier navigation bar.

Getting a Bit More Creative: Implementing a Variation of the Original Navigation Bar

As noted in the introduction, it’s fairly easy to tweak the behavior of the navigation bar created before, so that its buttons can be horizontally animated with jQuery. But before we come to that point, first it’s let's define the bar’s base structure. 

In this particular case, I’ll be following a typical approach, since the bar’s skeleton will be seated on top of an unordered list. The following web page accomplishes this in a snap. Check it out:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic nagivation bar using the 'background-position' CSS property</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.backgroundPosition.js"></script>
<script type="text/javascript" src="js/buttons.js"></script>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h2>Header section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
    <ul id="navbar">
        <li id="about"><a href="#" title="About Us">About Us</a></li>
        <li id="services"><a href="#" title="Services">Services</a></li>
        <li id="products"><a href="#" title="Products">Products</a></li>
        <li id="contact"><a href="#" title="Contact us">Contact</a></li>     
    </ul>
    <div id="main">
        <h2>Main section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
    <div id="footer">
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
         <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
</div>
</body>
</html>

If you had the chance to take a peek at the preceding tutorial, the above code fragment should be familiar to you, as the markup of the navigation bar is composed of the aforementioned unordered list, which has been used as a wrapper for the corresponding links.

With this simple – yet clean structure up and running already, the next logical step is to spice up its visual presentation with some straightforward CSS styles.

Polishing the Navbar’s Appearance: Defining a Simple CSS File

Providing the navigation bar look with a more appealing appearance is as simple as styling its links and the wrapping unordered list. In this case there’s a little catch: since the purpose here is to horizontally animate the, it’s necessary to use a different CSS sprite that permits us to implement this effect.

To better understand how this brand new sprite will be used in the creation of this animation, be sure to download the navigation bar’s supporting files here.

Having clarified that, take a look at the following CSS file, which performs the styling process:

(css/styles.css)

body {
    padding: 0;
    margin: 0;
    background-color: #1577a4;
    font: normal 0.9em Arial, Helvetica, sans-serif;
    color: #000;
}
h2 {
    margin: 0 0 10px 0;
    font-size: 2em;
    color: #1592cc; 
}
p {
    margin: 0 0 15px 0;
    line-height: 1.3em;
}
/* main wrapper */
#wrapper {
    width: 800px;
    margin: 0 auto;
    background-color: #fff;
}
/* header, main and footer elements */
#header, #main, #footer {
    padding: 20px;
}
/* navigation bar */
ul#navbar {
    list-style: none;
    width: 652px;
    padding: 0;
    margin: 0 auto;
    overflow: auto;
}
/* list items in navigation bar */
ul#navbar li {
    float: left;
    width: 162px;
    height: 57px;
    margin-right: 1px;
    background: transparent url("../images/sprite_vertical.png") no-repeat;
}
/* anchors in navigation bar */
ul#navbar li a {
    display: block;
    width: 162px;
    height: 57px;
    text-indent: -9999px;
}
/* 'About Us' button */
ul#navbar li#about {
    background-position: 0 0;
}
/* 'Services' button */
ul#navbar li#services {
    background-position: 0 -57px;
}
/* 'Products' button */
ul#navbar li#products {
    background-position: 0 -114px;
}
/* 'Contact' button */
ul#navbar li#contact {
    background-position: 0 -171px;
}


The above CSS styles are extremely easy to follow. Aside from defining the appearance of the H2 elements and paragraphs of the corresponding (X)HTML document (plus a few containers), they’re responsible for styling each button of the navigation bar, namely its “About Us”, “Services”, “Products” and “Contact” sections.

Here, it’s clear to see that this process is achieved by changing the X,Y coordinates of the provided CSS sprite, so if you haven’t done so already, go ahead and download the supporting material right away.

So far, so good. If at this point you test the navigation bar in its current state, it should look similar to this:







Admittedly, its appearance is quite appealing, but also pretty boring as well, as its buttons are simply static elements. Well, it’s time to fix this issue and to bring them to life with jQuery! 

Making Things More Dynamic: Horizontally Animating the Navigation Buttons

Horizontally animating the buttons of the navigation bar when hovering on them doesn’t differ too much from doing the same in a vertical fashion. Considering that the CSS sprite that permits us to do this was created already, the whole animation script is reduced to altering the X,Y coordinates of each button with the “Background Position” plug-in and nothing more.

Look at the following code snippet, which shows you how to achieve this:

(js/buttons.js)

$(document).ready(function() {
    // animate the 'About Us' button
    $("#about").hover(
        function() {
            $(this).stop().animate({backgroundPosition: "(-162px 0)"}, {duration: 300});

        },
        function() {
            $(this).stop().animate({backgroundPosition: "(0 0)"}, {duration: 300});
        }
    );
    // animate the 'Services' button
    $("#services").hover(
        function() {
            $(this).stop().animate({backgroundPosition: "(-162px -57px)"}, {duration: 300});

        },
        function() {
            $(this).stop().animate({backgroundPosition: "(0 -57px)"}, {duration: 300});
        }
    );
    // animate the 'Products' button
    $("#products").hover(
        function() {
            $(this).stop().animate({backgroundPosition: "(-162px -114px)"}, {duration: 300});

        },
        function() {
            $(this).stop().animate({backgroundPosition: "(0 -114px)"}, {duration: 300});
        }
    );
    // animate the 'Contact Us' button
    $("#contact").hover(
        function() {
            $(this).stop().animate({backgroundPosition: "(-162px -171px)"}, {duration: 300});

        },
        function() {
            $(this).stop().animate({backgroundPosition: "(0 -171px)"}, {duration: 300});
        }
    );
});


The functionality of the above script is reduced to animating the “background-position” property of each button of the navigation bar through the “Background Position” plug-in, which in this case is used within jQuery’s animate()” method. Of course, there’s no shortage of options when it comes to customizing the script’s current behavior; however, if you give it a try using your own browser, the buttons should be displaced horizontally when hovering on them, as shown in the image below:



There you have it. In a few easy steps, you learned how to create an animated navigation bar, which can be easily tweaked with minor hassles. So, what are you waiting for? Go ahead and start adding to it your own improvements!

Final Thoughts

Over this two-part tutorial, I demonstrated in a step-by-step fashion, how the clever usage of the “background-position” CSS property can be of great help in the construction of dynamic user interfaces, such as the sample navigation bar that you saw before. Thus, if you’re planning to spice up your web site with a fresh touch that keeps your users coming back for more, the use of animated CSS sprites can be the solution that you’re looking for.

See you in the next web design tutorial!