How to Make the Sticky Header on Scroll

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

Pitamber Singh
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.