All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Create Sticky Header Using jQuery And CSS

Last Updated : Jul 1, 2023

IN - jQuery CSS | Written & Updated By - Dikshita

In this tutorial we will show you how to create sticky header using jQuery and CSS, sticky Header is a term generally used for page header which is stick or fixed at the top and does not scroll with the page that make the header always visible to user while scrolling the page.

You may also like Animated Navigation Menu Using CSS.

Create Sticky Header Using jQuery And CSS

To Create Sticky Header It Takes Only Two Steps:-

  1. Make a HTML file and define markup and scripting
  2. Make a CSS file and define styling

Step 1. Make a HTML file and define markup and scripting

We make a HTML file and save it with a name header.html

<html>
<head>
<link rel="stylesheet" href="header_style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(window).scroll(function() 
{
 if ($(this).scrollTop() > 1)
 {
  $('#header').addClass("sticky_header");
 }
 else
 {
  $('#header').removeClass("sticky_header");
 }
});
</script>
</head>
<body>

<div id="header" class="big_header">
 <p>TalkersCode Sticky Header</p>
</div>

<div id="wrapper">
 <h1>Sticky Header Using jQuery And CSS</h1>
 <p>Scroll Down To View Changes In Header</p>
</div>

</body>
</html>

In this step we create two div one is for our page header other is for page body. We use window.scroll() function to detect the scroll and when user scroll and the distance between top and scroll is larger than 1px we change the header class to make our header small.

You may also like Slide In Navigation Menu Using jQuery And CSS.

Step 2. Make a CSS file and define styling

We make a CSS file and save it with a name header_style.css

body
{
 text-align:center;
 width:100%;
 margin:0 auto;
 padding:0px;
 font-family:helvetica;
 background-color:#E6E6E6;
}
.big_header
{
 top:0px;
 position:fixed;
 width:100%;
 background-color:#084B8A;
 color:white;
 font-size:40px;
 z-index:2;
 transition: all 0.3s ease;
}
.sticky_header
{
 font-size: 17px;
}
#wrapper
{
 position:relative;
 top:150px;
 text-align:center;
 margin:0 auto;
 padding:0px;
 width:995px;
 height:1000px;
}
h1
{
 margin-top:50px;
 color:#585858;
 font-size:55px;
}

In this step we create two class for header .big_header is used before scrolling and .sticky_header is used after scrolling when the distance from top and scrollbar is larger than 1px.

You may also like Custom Scrollbars Using CSS And HTML.

Thats all, this is how to create sticky header using jQuery and CSS. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on sticky header css helps you and the steps and method mentioned above are easy to follow and implement.