DEV Community

Cover image for Are You Stuck on Sticky?
Max Zander
Max Zander

Posted on

Are You Stuck on Sticky?

So lately, a few people have been asking me about the sticky navbar on the website I built for a small crafting business called Adrian's Dream. If you're not really sure what that means, it looks a little something like this:
A GIF of the Adrian's Dream website with its sticky navbar

Take a look at the navbar in that GIF. See how it isn't scrolling with the page? That's a sticky navbar.

Now, since it has come up enough, I figured I'd write a quick post about how to do it and I promise accomplishing it is way easier than you might think.
(Spoiler Alert: We're doing it with CSS!)

So first off, I want to briefly review the position CSS property. According to the Mozilla Docs:

The position CSS property sets how an element is positioned in a document. The top, right, bottom, and left properties determine the final location of positioned elements.

Now, not to go all here's-my-life-story-before-the-recipe on you, but before I tell you how to do it, I want to mention that the default value of the position property is position: static. What that means is that the element with a static property will be positioned in a set place in the document, so if you scroll, the element will scroll along with everything else on the page.

So how do we create a sticky navbar? Simple! We use position: sticky!

Let's say we have a navbar with a className of "navbar" (<nav className="navbar">). If we (amongst the rest of our CSS) add our position and top as follows:

.navbar {
    position: sticky;
    top: 0;
}
Enter fullscreen mode Exit fullscreen mode

Now we have a navbar that is positioned at the very top of the document and, if we scroll down, it will be stuck to that position (not scrolling along with everything else). Boom. Easy, right?

Now go forth and code!

Top comments (0)