Sticky header using CSS and JavaScript

Java Script @ Freshers.in

A sticky header refers to a website navigation tool that remains in a fixed position at the top of the screen as the user scrolls down the page. In other words, instead of scrolling out of view as you scroll down the page, a sticky header stays in the same place, ensuring that the header’s content (often including navigation links, logos, and other important information) is always accessible to the user, no matter how far they’ve scrolled.

The main advantage of using sticky headers is improved user experience. Having constant access to key navigation can make browsing and interacting with a website more user-friendly, especially for long pages.

The CSS property responsible for this behavior is position: sticky;. It acts like a regular position relative until an element’s container is in view, at which point the element sticks in place (like position fixed).

header {
  position: -webkit-sticky; /* For Safari */
  position: sticky;
  top: 0;
}

This CSS will make the header element stick to the top of the viewport when scrolling. The top: 0; defines the distance from the top of the viewport.

Here’s a simple example of a sticky header using CSS and JavaScript:

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sticky Header</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header class="header" id="myHeader">
        Sticky Header @ Freshers.in
    </header>
    <main>
        <!-- Your main content here -->
        <p>
            Freshers.in Learning Website         </p>
        <!-- Repeat paragraphs or other content to see the sticky effect -->
    </main>
    <script src="scripts.js"></script>
</body>
</html>

CSS (styles.css)

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
}
.header {
    background-color: #f5f5f5;
    padding: 10px 20px;
    width: 100%;
    position: sticky;
    top: 0;
    z-index: 10; /* Ensures the header is always on top */
    transition: all 0.3s; /* Smooth transition effect */
}
.sticky {
    background-color: #333; /* Change to desired sticky color */
    color: #fff;
}
main {
    padding: 20px;
}

JavaScript (scripts.js)

window.onscroll = function() {
    stickyHeader();
};
var header = document.getElementById("myHeader");
function stickyHeader() {
    if (window.pageYOffset > 0) {  // Adjust this value if needed
        header.classList.add("sticky");
    } else {
        header.classList.remove("sticky");
    }
}

In this example, when you scroll past the specified offset (in this case, just past the top of the page), the header will get the .sticky class added to it, changing its color.

Author: user

Leave a Reply