Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Create a Fixed/Sticky Header on Scroll with CSS and JavaScript?
Next article icon

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

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content=           "width=device-width, initial-scale=1.0">     <title>Fixed Header</title>     <style>         body {             margin: 0;             font-family: Arial, sans-serif;         }          header {             background-color: rgb(19, 179, 19);             color: white;             padding: 10px 20px;             position: relative;             width: 100%;             transition: top 0.3s;         }          header.fixed {             position: fixed;             top: 0;             z-index: 1000;         }          h3 {             color: green;         }          main {             padding: 20px;             height: 2000px;             background-color: #ccc6c6;         }     </style> </head>  <body>     <header id="header">         Fixed Header     </header>     <main>         <h3>Welcome to GeeksForGeeks</h3>         <h4>Scroll down to see the fixed header in action.</h4>         <p>             GeeksforGeeks (GFG) is a computer science             portal founded by Sandeep Jain in 2009.             It started as a blog to share computer             science concepts and has grown into a             comprehensive platform for learning             and practicing coding. It is based in             Noida, Uttar Pradesh, India.         </p>         <p>Industry: E-Learning, EdTech Product,             Services and Operations: Provides a wide              range of articles on various topics related to              computer science and programming. Offers             practice problems and coding competitions              for users to improve their coding skills.             Provides interview experiences and preparation             resources for tech job aspirants. Offers online             courses and tutorials on various tech topics.</p>         <p>             Funding Details: The company is privately             owned and does not disclose its financial details.             Acquisitions: No notable acquisitions.              Awards and Achievements: Recognized as one             of the most popular computer science portals             in India.- Has a large user base of millions of             users worldwide. Please note that the information             provided is based on the available resources             and may not be 100% accurate.         </p>      </main>      <script>         window.addEventListener('scroll', function () {             const header = document.getElementById('header');             if (window.scrollY > 50) {                 header.classList.add('fixed');             } else {                 header.classList.remove('fixed');             }         });     </script> </body>  </html> 

Output:


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

Y

yuvraj07
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

    How to Create Shrink Header on Scroll using HTML, CSS and JavaScript ?
    The Shrink Navigation bar works when the user scrolls down the page. In this article, we will use HTML, CSS, and JavaScript to design a shrink navigation bar. HTML is used to create the structure, and CSS is used to set the style of the HTML structure to make it looks good. This kind of shrinking na
    3 min read
    How to Create Sticky Header/Footer on a Web Page using HTML CSS and JavaScript?
    When designing a website, it's essential to consider the sticky header and footer. These elements enhance the user experience by keeping important navigation links accessible as users scroll. This article explores creating sticky headers and footers with CSS.We can do this by using the following CSS
    7 min read
    How To Create a Table With Fixed Header and Scrollable Body?
    Here are the methods to create a table with a fixed header and a scrollable body.Before proceeding, enhance your understanding by exploring this comprehensive guide on HTML tables.1. Using position: sticky and overflow-yThis method employs position: sticky on the table header to keep it fixed at the
    3 min read
    How to Get and Set Scroll Position of an Element using JavaScript ?
    In this article, we will learn how to get and set the scroll position of an HTML element using JavaScript.Approach: We will be using the HTML DOM querySelector() and addEventListener() methods and the HTML DOM innerHTML, scrollTop and scrollLeft properties.We create an HTML div element with an id of
    3 min read
    How to Create a Change Background on Scroll using HTML CSS and JavaScript ?
    In this article, we will try to change the background color of the container once the scroll occurs. If a user scrolls down the page the background color will be changed. We will use the below approach to accomplish this task.Using the scroll event on the window objectIn this approach, we will use t
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences