VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-create-a-fixed-sticky-header-on-scroll-with-css-and-javascript/

⇱ How to Create a Fixed/Sticky Header on Scroll with CSS and JavaScript? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Create a Fixed/Sticky Header on Scroll with CSS and JavaScript?

Last Updated : 5 Aug, 2025

A fixed or sticky header remains at the top of the webpage when the user scrolls down. This functionality enhances navigation and user experience by keeping important links always visible. In this article, we will explore the approach to creating a fixed/sticky header on scroll using CSS and JavaScript.

Approach

  • Create a basic HTML structure with a header element for the fixed header and a main element to some content.
  • Add some content inside main element using <p> tag.
  • Style the header such as a background color, text color, padding, and width. We will set position: relative initially.
  • Add padding to the main element and set a height to create enough scrollable content.
  • We use JavaScript to add an event listener for the scroll event on the window object.
  • Inside the event listener get a reference to the header element using its id.
  • We will use window.scrollY to get the current scroll position.
  • When the scroll position becomes greater than a specified value, we add the fixed class to the header. Otherwise we remove it.

Example: Implementation to create a fixed/sticky header on scroll with CSS and JavaScript.

Output:

Comment
Article Tags: