How to resize and sticky header on scroll

In this snippet, we learn how to create the header which can resize and sticky when user scroll.

Step 1: Add Header element to your HTML files

<div id="header">
  <div class="logo">Logo</div>
  <ul class="menu">
    <li>home</li>
    <li>about</li>
    <li>products</li>
    <li>contact</li>
  </ul>
</div>
Copy this code

Note: For window scroll bar visibility, you have to add more content or set height for body.

Step 2: Add CSS code below to your style file

#header {
  background-color: #f1f1f1;
  padding: 50px 20px;
  color: black;
  position: fixed;
  top: 0;
  width: 100%;
  transition: 0.2s;
}
#header.sticky {
 background-color:#4CAF50;
    color: white;
    padding: 10px 20px;
}
#header.sticky .logo {
 font-size:28px;
}
.logo {
 float:left;
    font-size:38px;
    width:40%;
    font-weight: bold;
}
.menu {
 float:right;
    list-style:none;
    width:60%;
    margin:0; padding:0;
}
.menu li{
 float:left;
    font-size:18px;
    padding:5px 10px;
}
Copy this code


Step 3: Add the Javascript codes below

 window.onscroll = function() {onScroll()};
function onScroll() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("header").classList.add("sticky");
  } else {
    document.getElementById("header").classList.remove("sticky");
  }
}
Copy this code

In the Javascript codes above, we check when the user scrolls down 50px from the top of the document, add class sticky to the header.


Demo: