The Wayback Machine - https://web.archive.org/web/20240907053012/https://www.geeksforgeeks.org/how-to-create-a-fixed-sticky-header-on-scroll-with-css-and-javascript/
Open In App

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
Save
Share
Report
News Follow

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:



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 navbar looks attractive on a site. By using JavaScri
3 min read
Hide scroll bar, but while still being able to scroll using CSS
Hiding the scrollbar with CSS enhances webpage aesthetics by removing visible scrollbars while maintaining scroll functionality. This can be achieved using browser-specific CSS properties for Chrome, Safari, Firefox, and Internet Explorer, ensuring a cleaner, more streamlined user interface without sacrificing usability. There are many other option
3 min read
How to Click on header to add another header in jQuery ?
In this article, we will see how to add a new header element after clicking the existing header elements in jQuery. To add the new header element, the delegate() method is used. Syntax: $(selector).delegate("Selected_elements", function() { $(this).after("content"); }) Here, we use delegate() method to add one or more event handlers to the specifie
1 min read
How to define whether a header cell is a header for a column, row, or group of columns or rows in HTML 5?
In this article, we will learn how to specify whether a header cell is a header of a column, row, or group of columns or rows. The &lt;th&gt; tag is used to specify the heading for an &lt;table&gt; element, typically for the columns of the table. However, in specific cases, the header can be used to define the heading of a row or a group of columns
2 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 the scroll event on the window object and pass a c
6 min read
How to Create Scroll Indicator using HTML CSS and JavaScript ?
Scroll Indicator is a progress bar that represents how much a page has been scrolled. When we scroll down the bar fills up and when we scroll up the bar amount reduces. Approach: Now, we will create a basic webpage with text to enable scrolling and then use JavaScript to make the scroll indicator work. HTML Code: In this section, we will create a b
3 min read
Create an Infinite Scroll Page using HTML CSS & JavaScript
In this article, we will create an infinite scroll page using HTML, CSS, and JavaScript. Infinite scrolling allows you to load and display content as the user scrolls down the page, providing a seamless browsing experience. We'll fetch and append new content dynamically as the user reaches the end of the current content. Preview Image: Approach:We'
2 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 propertiesPosition: sticky; is a CSS property th
7 min read
How to create a bounce in and out on scroll effect using CSS ?
Creating a bounce in and out on the scroll effect can add an exciting and engaging touch to your web design. This effect creates a bouncing animation when the user scrolls down the page, and then bounces back when the user scrolls up. In this article, we will discuss the syntax and approaches to create this effect, followed by at least two examples
3 min read
How to create Horizontal Scroll Snap Using HTML and CSS ?
In this project, we are going to create a simple Horizontal Scroll Snap by using HTML and CSS only. Glimpse of Project Approach: The best way to animate the HTML objects is by using CSS classes and by setting the transitions at different stages. HTML code:Create an HTML file (index.html).Link the CSS file in HTML that provides all the animation’s e
2 min read
Create Animated Scroll-to-Top Button in Tailwind CSS
An animated scroll-to-top button is a user interface element that appears on a webpage when the user scrolls down. It allows the user to quickly return to the top of the page with a single click or tap. This feature is often implemented using CSS animations or transitions, and it can enhance the user experience by providing a convenient way to navi
2 min read
How to create a Scroll Back to Top button using CSS ?
Scrolling the webpage can be a tedious task especially when you are somewhere at the bottom of the page &amp; the length is too long to again reach the top of the webpage. The user may sometimes escape to visit the page. For this, adding a scroll-back button can help to reach the initial position of the page. Here, the button is initially hidden an
3 min read
Slide Down a Navigation Bar on Scroll using HTML, CSS and JavaScript
To create a slide down navigation bar you need to use HTML, CSS, and JavaScript. HTML will make the structure of the body, CSS will make it looks good. This kind of sliding navbar looks attractive on a site. By using JavaScript you can easily make the navigation bar slideable when the user scrolls down. Creating Structure: In this section, we will
4 min read
How to create Non-Rectangular Header using HTML &amp; CSS ?
In this article, we are going to create a Non-Rectangular-header using the basics of HTML and CSS. Approach: Create a header using &lt;header&gt; tag.Create a div for adding the content for the header.Use clip-path() function to give a particular shape to the header. HTML Code: Create an HTML file (index.html).Link the CSS file that provides all th
1 min read
What is the difference between overflow: auto and overflow: scroll in CSS ?
In this article, we will understand the difference between the `scroll` &amp; `auto` values for the overflow CSS shorthand property. The Overflow property specifies the preferred behaviors for an element's overflow i.e., when the content of an element is too large to fit within its block formatting context in both directions. In simple words, it co
3 min read
How to create a Scroll To Top button in React JS ?
You will see there are lots of websites, that are using a useful feature like if you're scrolling the webpage, and now you are at the bottom of that page then you can use this button to scroll up automatically like skip to the content. The following example covers create a Scroll To Top button in React JS using useState() hook. Prerequisite: Basic
4 min read
How to Create Scroll Indicator using ReactJS ?
Scroll Indicator in React JS refers to a representation of the length of the page visited or present on the screen. It shows the amount the pages that have been scrolled. PrerequisiteNode.js &amp; npm React JSstyled-componentsReact JS useState() hooks.Approach to create Scroll IndicatorTo create a Scroll Indicator using ReactJS we will use a scroll
2 min read
How to create a Scroll To Bottom button in React JS ?
Learn to implement a "Scroll to Bottom" button in React using the useState() hook, a feature commonly seen in chat applications like WhatsApp and Telegram for effortless navigation to the end of a chat window. Prerequisites:NodeJS or NPMReact JSstyled-componentReact useState()Steps to Create the React Application And Installing Module:Step 1: Creat
2 min read
How to create Table with 100% width, with Vertical Scroll inside Table body in HTML?
To add a vertical scroll bar inside the table body, use the overflow-y property. By changing the display property of tbody to block, we can display the block-level element. However, when changing the display property of tbody, we must also change the property of thead to prevent the table layout from breaking. ApproachApply the class scroll down to
2 min read
How to Create a Scroll Back-to-Top Button in WordPress?
The "Scroll Back-to-Top Button" in the website is a feature that looks like a button in the website, typically in the lower corner of the screen, which allows users to easily scroll back to the top of the page with a single click. A "Back to Top" button is a very easy little feature you often see on websites. When you click it, it takes you straigh
3 min read
Create a scroll status in ReactJS using Material-UI
Progress bars at the top, showing scroll status are very common nowadays in webpages. Also, ReactJS and Material-UI go pretty well along with each other, React-JS being the most popular JavaScript framework for building UI components and Material-UI a library that provides various useful and reusable react components. Prerequisites:NodeJS or NPMRea
3 min read
How to create a table with fixed header and scrollable body ?
The purpose of this article is to create a table with a fixed header and scrollable body. We can create such a table with either of the two approaches. By setting the position property to “sticky” and specifying "0" as a value of the top property for the &lt;th&gt; element.By setting the display to "block" for both &lt;thead&gt; and &lt;tbody&gt; e
2 min read
CSS | scroll snap
The CSS Scroll Snap is an inbuilt module. It introduces the scroll snap position to web technology. The scroll container's scroll-port work when the scrolling operation did its job. This module is new in HTML 5 before that there was a similar module known as Scroll Snap Point which has been removed and replaced by this Scroll Snap module. There are
3 min read
CSS | Scroll Snap type
The Scroll Snap type property is an inbuilt property in the Scroll Snap module. Without the Scroll Snap module, the image gallery will look ridiculous. Before the Scroll Snap module, this effect can be achieved by JavaScript but during this days Scroll Snap with the CSS can be achieved. This property is useful to stop scrolling at some specific poi
3 min read
CSS | Scroll Snap stop
The Scroll Snap stop property is an inbuilt property in the Scroll Snap module. The Scroll Snap stop property stops or you can lock the scroll at some specific position that you define. It works like there is a pattern in your every slide and when the user scrolls the slide the pattern automatically changed and fits into the background and fixes th
2 min read
CSS | Scroll Padding
The Scroll Padding property is an inbuilt property in Scroll Snap module. This property sets the scroll padding longhands. This property acts as a magnet on the top of the sliding element that sticks to the top of the viewport and stops the scrolling(forcefully) in that place. The Scroll Padding property is optional, this property is used when the
2 min read
CSS | Scroll Padding bottom
The Scroll Padding bottom is an inbuilt property in Scroll Snap module. This property set the scroll padding longhand. This property acts as a magnet on the top of the sliding element that stick to the top of the view-port and stop the scrolling(forcefully) in that place. The Scroll Padding property is optional, this property is used when the Scrol
2 min read
CSS | Scroll Padding top
The Scroll Padding top is an inbuilt property in Scroll Snap module. This property set the scroll padding top longhand. This property acts as a magnet on the top of the sliding element that stick to the top of the view-port and stop the scrolling(forcefully) in that place. The Scroll Padding property is optional, this property is used when the Scro
2 min read
How to set the overflow property to scroll in CSS ?
In this article, we will see how to set the overflow property to scroll in CSS. The overflow property is used to control the big content. It tells what to do when an element's content is too big to fit in the specified area. When the overflow property is set to scroll, the overflow is clipped, but a scrollbar is added to see the rest. Example 1: In
2 min read
CSS scroll-margin Property
The scroll-margin property is used to set all the scroll margins of an element at once. The value specified for the scroll-margin determines how much of the page that is primarily outside the support should remain visible. Hence, the scroll-margin values represent outsets that define the scroll snap area that is used for snapping this box to the su
2 min read
Article Tags :