Creating a sticky navigation bar
Updated: 05-Jan-2022 / Tags: HTML and CSS / Views: 652 - Author: George
Introduction
Hello guys.
In this tutorial we are going to do something easy. We are going to create a sticky navigation bar.
A navigation menu bar is called sticky when it sticks at the top of the page, but the rest of the content is scrollable. This is a usefull technique, because the user has the navigation always on sight when he scrolls the content.
Live Example
Click on the Live Demo button to see the navigation stick at the top of the page when you
scroll the content.
The html code
Let's see the html code that we need to re-create the live demo. We have here a simple navigation divided in two sections. In the first div we have the brandname and the logo image, and in the second div we have the links.
<body>
<nav class="sticky">
<div class="brand">
<img src="site-images/logo-3.png" alt="">
<span>I am a sticky navbar</span>
</div>
<div class="links">
<a href="#">Home</a>
<a href="#">Blend</a>
<a href="#">Benefits</a>
<a href="#">About Us</a>
<a href="#">Contact</a>
</div>
</nav>
</body>
The css rules
Here we have the styling of our navbar, but the property that will do the trick and will glue the navbar to the top of the page is the position:sticky in line 9.
But we have also to specify where we want the nav element to stick.
Here comes the top and left property.
The values that we set to these properties will tell the navbar or any element,
where to stop scrolling and stay in place.
In our our example we set the values to zero so the navbar sticks to the top of the page.
Also we have to set a high z-index to the navbar so the content will scroll under.
nav{
height: 70px;
display: grid;
grid-template-columns: 1fr 1fr;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.10);
background-color: #ffffff;
/* We need to set the position property to sticky */
position: sticky;
top: 0; /* Zero pixels on the Y axis */
left: 0; /* Zero pixels on the X axis */
z-index: 99; /* And a high z-index value */
}
Have in mind that the navbar will stick to the top as long the container it belongs to, has content.
The best practice is to place the navbar in a high order parent element such the body element.
Summary
To create an element that sticks on the page as we scroll, wehave to use the position css property and set its value to sticky.
Also we have to set the top and left property to define where in the page the element will stick.
In example, if we set a value of 100px in the top property, top:100px, the element will stay in place 100 pixels down from the top of the page.
Source code
You can download the source code and use it in any way you like.
Times downloaded: 46
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉