How to create a "sticky" navbar with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

Following is the code to create a sticky navbar using css and javascript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
   margin:0px;
   margin-top:10px;
   padding: 0px;
   height: 150vh; /* To produce scrolling effect */
}
nav{
   width: 100%;
   background-color: rgb(39, 39, 39);
   overflow: auto;
      height: auto;
}
.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   color: rgb(178, 137, 253);
   text-decoration: none;
   font-size: 17px;
}
.links:hover {
   background-color: rgb(100, 100, 100);
}
.selected{
   background-color: rgb(0, 18, 43);
}
.fixed{
   position:fixed;
   top:0;
}
.fixed + .sample-content{
   padding-top: 60px;
}
</style>
</head>
<body>
<div class="sample-content">
<h1>Here are some headers</h1>
<h2>Here are some headers</h2>
<h3>Here are some headers</h3>
<h4>Here are some headers</h4>
</div>
<nav>
<a class="links selected" href="#"> Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#">More Info</a>
</nav>
<div class="sample-content">
<h1>Here are some headers after nav</h1>
<h2>Here are some headers after nav</h2>
<h3>Here are some headers after nav</h3>
<h4>Here are some headers after nav</h4>
</div>
<script>
window.onscroll = scrollShowNav;
let navEle = document.getElementsByTagName("nav")[0];
let stickyTop = navEle.offsetTop;
function scrollShowNav() {
   if (window.pageYOffset >= stickyTop){
      navEle.classList.add("fixed");
   } else {
      console.log('WOW');
      navEle.classList.remove("fixed");
   }
}
</script>
</body>
</html>

Output

The above code will produce the following output −

On scrolling to the specified position, the navbar will act as position: fixed like shown below −

raja
Published on 03-Apr-2020 11:04:11
Advertisements