How to Make the Sticky Header on Scroll

Updated on:19 Jun 2020, 17:10pm IST

In this tutorial we will teach you how to make the sticky header on scroll using HTML, CSS and Jquery.

Team Markup Infinity

HTML

<header class="header">
	<div class="container">			
		<a class="logo" href="#">Site Title</span></a>
		<nav>
			<ul>
				<li><a href="#">Home</a></li>
				<li><a href="#">About</a></li>
				<li><a href="#">Gallery</a></li>
				<li><a href="#">Services</a></li>
				<li><a href="#">Portfolio</a></li>
				<li><a href="#">Contact</a></li>
			</ul>
		</nav>
	</div>
</header>

Css

body{margin:0; padding:0; line-height: 22px; font-family:'arial'; font-size:16px; color:#c2c2c2; background:#100e17;}
body.headerFixed{padding: 71px 0 0 0;}
.container{max-width: 1170px; padding: 0 15px; margin: 0 auto;}
.header{width:100%; float:left; background:#000; padding:12px 0 17px 0; transition: all ease .2s;}
.logo{display: inline-block; vertical-align: top; font-size: 28px; color: #fff; font-weight: 700; text-decoration: none; margin: 12px 0 0 0;}
.header nav{float: right;}
.header nav ul{width: 100%; float: left; list-style: none; margin: 0; padding: 0;}
.header nav ul li{display: inline-block; vertical-align: top; padding: 10px;}
.header nav ul li:first-child{padding-left: 0;}
.header nav ul li a{text-decoration: none; color: #b6e8ff ; text-transform: uppercase; transition: all ease 0.3s; -webkit-transition: all ease 0.3s;}
.header nav ul li a:hover{color: #fff;}
.header-fixed{width: 100%; top: 0; left: 0; z-index: 2; position: fixed; animation: 1s ease 0s normal none 1 running bounce; -webkit-animation: 1s ease 0s normal none 1 running bounce; }
@keyframes bounce{
	0%{top:-100%; z-index:1;}
	100%{top:0;}
}
.section1{width: 100%; float: left; height: 100vh; background:green;}
.section2{width: 100%; float: left; height: 100vh; background:orange;}

Jquery

$(window).scroll(function(){
  var sticky = $('.header'),
  scroll = $(window).scrollTop();
  if (scroll >= 71) sticky.addClass('header-fixed');
  else sticky.removeClass('header-fixed');
});

$(window).scroll(function(){
  var sticky = $('body'),
  scroll = $(window).scrollTop();
  if (scroll >= 71) sticky.addClass('headerFixed');
  else sticky.removeClass('headerFixed');
});

To check the demo, click here

If you are a beginner and wants to try your hand in Full Stack Development, then must check out remotestack.io

user

Team Markup Infinity

Technology is such a broad kind of term, it really applies to so many things, from the electric light to running cars on oil. All of these different things can be called technology.