Main Menu

Sticky Position (Bar) with CSS or jQuery

The idea of ‘sticky position’ is to make elements on a website stick and remain visible. Those elements will initially be in their position, and then in the event of scrolling down the webpage, their position will be following the scroll. This practice has been applied wildly including on a few notable websites, such as Facebook and Hongkiat.com.

In Facebook, this technique has been applied to their sidebar; when we scroll down the page, you will find that it follows the scroll and thus remains visible.

Over all the years, this practice is done using JavaScript or jQuery, as follows.

The jQuery Way

In this example, we will create a simple webpage that consists of the header, the navigation and the content.

All right, this way is probably a bit convoluted for those who are not familiar with jQuery as a whole. Alternatively, to achieve the same effect is a bit easier with jQuery – you can use a plugin, ScrollToFixed. Or else, let’s take a look at another way with CSS.

The CSS Way

Recently, Webkit introduced a new position value that is simply called sticky, and it does the same thing the jQuery code above does. However, since this sticky value is still determined as experimental feature, we need to first enable this feature.

Assuming that your current Chrome is version 23 and above, you can type the following in the address bar: chrome://flags. Otherwise, you need to first update it.

Then, find the following section, Enable experimental WebKit features on the list and set this feature to Enable.

In the stylesheet, we simply set the navigation position to sticky. But, since it is only available on Webkit, it will only work with the prefix, like so.

.nav {
position: -webkit-sticky;
top: 0;
z-index: 1;
}

Now, the navigation should act in the same way as we did with jQuery. See the demo below in Google Chrome Canary to see it in action.