How To Create a Sticky Navbar | Sticky Top Navbar
<div class="text">
<h2>Sticky navigation bar</h2>
</div>
<div class="nav">
<div class="logo">
<a href="#">CWR</a>
</div>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
<section>
</section>
<section>
</section>
<section>
</section>
There is all the HTML code for the Sticky Top Navbar. Now, you can see an output with Sticky Top Navbar then we write javascript for sticky Top Navbar.
body
{
margin: 0;
padding: 0;
font-family: arial, sans-serif;
}
.text{
text-align: center;
height: 100px;
background: #262626;
color: #FFF;
}
.text h2{
margin: 0;
line-height: 100px;
font-size: 48px;
}
.nav{
background: #CA3400;
color: #FFF;
display: flex
}
.nav .logo{
font-size: 24px;
padding: 20px;
margin-left: 25px
}
.nav .logo a{
color: #FFF;
text-decoration: none
}
.nav ul{
margin: 0;
padding: 0;
display: flex;
width: 50%;
margin-left: auto
}
ul li{
padding: 20px;
list-style: none
}
ul li a{
color: #FFF;
display: block;
text-decoration: none;
text-transform: uppercase;
font-weight: bold
}
section{
height: 300px;
}
.sticky{
position: fixed;
top: 0;
left: 0;
width: 100%
}
Css Updated output
cdn link > https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js
$(window).scroll(function(){
if($(this).scrollTop() > 100){
$('.nav').addClass('sticky')
} else{
$('.nav').removeClass('sticky')
}
});
Final output
Now that we have completed our javascript section, Here is our updated output with javascript. Hope you like the sticky Top Navbar. you can see the output video and project screenshots. See our other blogs and gain knowledge in front-end development. Thank you 🙏💕!
In this post, we learn how to create a sticky Top Navbar using simple HTML & CSS, and javascript. If we made a mistake or any confusion, please drop a comment to reply or help you in easy learning.
Written by – Code With Random/Anki
Code by – @Eslam_Refa3y