Show me a code snippet of a website’s sticky header in CSS and JavaScript.

Certainly! A sticky header is a header that remains fixed at the top of the page while the user scrolls down. Below is a simple example of how you can create a sticky header using HTML, CSS, and JavaScript:


<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Sticky Header Example</title>
<header id="sticky-header">
<h1>Sticky Header</h1>

<!-- Content goes here -->

<script src="script.js"></script>

CSS (styles.css):

body {
margin: 0;
font-family: 'Arial', sans-serif;

header {
background-color: #333;
color: #fff;
padding: 10px;
text-align: center;

/* Add a top margin to the content to prevent it from being hidden behind the sticky header */
body {
margin-top: 60px; /* Height of the sticky header */

/* Style for the sticky header */
#sticky-header {
position: fixed;
top: 0;
width: 100%;

JavaScript (script.js):

// Get the header element
var header = document.getElementById("sticky-header");

// Get the offset position of the header
var sticky = header.offsetTop;

// Function to add the "sticky" class to the header when you reach its scroll position
function stickHeader() {
if (window.pageYOffset > sticky) {
} else {

// Listen for scroll events and call the stickHeader function
window.onscroll = function() {

In this example, the header becomes sticky when you scroll down the page, and the sticky class is added to the header using JavaScript. The CSS defines the styles for both the regular and sticky headers. The content has a top margin to ensure it is not hidden behind the sticky header. Adjust the styles and structure based on your specific requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *