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:

HTML:

html
<!DOCTYPE html>
<html lang="en">
<head>
<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>
</head>
<body>
<header id="sticky-header">
<h1>Sticky Header</h1>
</header>

<!-- Content goes here -->

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

CSS (styles.css):

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):

javascript
// 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) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}

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

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 *