How TO - Sticky/Affix Navbar
Learn how to create a "sticky" navbar with CSS.
How To Create a Sticky Navbar
Step 1) Add HTML:
Create a navigation bar:
Example
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
Step 2) Add CSS:
Style the navigation bar; addposition:sticky andtop:0 to make the navbar stick when you reach its scroll position:
Example
#navbar {
position: sticky;
top: 0;
overflow: hidden;
background-color: #333;
}
/* Navbar links */
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px;
text-decoration: none;
}
/* Page content */
.content {
padding: 16px;
}
An element withposition: sticky; is positioned based on the user's scroll position.
A sticky element toggles betweenrelative andfixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
Note:You must specify at least one oftop,right,bottom orleft for sticky positioning to work.
To learn more about CSS positoning, read ourCSS Position tutorial.

