Easy-to-Code Navigation that Scrolls With You: It’s Possible!

These days, navigation that follows a user down the page is a very attractive and user-friendly design. When a user doesn’t have to scroll all the way back to the top of the page to get to the navigation, and doesn’t even have to fool with clicking a “back to top” link, it’s a wonderful thing.

But it’s a little challenging for us web designers to get it done, as I discovered while researching for this blog post; there are plenty of designers looking for ways to make this happen in their own layouts, and there are just as many solutions in various programming languages.

Eventually, I just opened my trusty Notepad++ and started knocking together some code myself–and I accidentally found a very, very simple CSS solution.

Robin’s Sticky Nav Bar: The (Code) Recipe

Click to see my simple “sticky nav bar” demo! (opens in new window)

To make the above page navigation work, it took about an hour of experimenting with HTML and CSS, creating a dummy layout and the like. But finally, on a whim, I stuck the following bits of code into my navbar div:

The code in bold above is the important bit to see here; this was the magic wand that transformed my plain ol’ horizontal navbar. Once you style your own navbar the way you want it, all it takes is two code bits–“position: fixed;” and “top: 0px;”–to make it stick to the top of the page.

And, to make it centered like the rest of my layout, I made sure to put my navbar div within a container div called “wrap,” styled like so:

#wrap {width: 900px; margin: 0px auto; padding: 0px;}

The following HTML code is what I mean by “putting the ‘navbar’ div within the ‘wrap’ div:”

That’s really all the magic there is to it! (This design works in Firefox, IE, and Chrome; I have not tested it in any other browsers, but it seems that these three handle it identically, so I have hope that it works with all browsers similarly. If you find that this code doesn’t work in a browser I haven’t tested, let me know!)

One Small Caveat:

Fixing your navbar to the top of the page with “position: fixed” works great–but only if you don’t mind your navbar being the very topmost thing to display on your layout. If your ideal navbar is located beneath your header image to begin with, but then sticks to the top of the page when your user scrolls down, then just using “position: fixed” with a different pixel value in “top:” won’t make that happen. (Believe me, I tried–it was fail. I ended up with a navbar just stuck randomly in the middle of the page blocking the content. :/)

So, what to do if you want a navbar that will stick to the top of the page, even if it’s not at the tip-top of the layout to begin with? Well, from what I found in my research, you’re likely going to have to use Javascript/jQuery to make this more complex navbar. Here are two forum/discussion sites which explain these methods much better than I ever could.