Certainly! A sticky header is a common feature on websites where the header stays fixed at the top of the page as you scroll down. Here’s a simple example using HTML, CSS, and JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
header {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
}
section {
padding: 20px;
margin-top: 60px; /* Adjust margin-top to accommodate the fixed header */
}
</style>
</head>
<body>
<header>
<h1>Sticky Header</h1>
</header>
<section>
<p>This is the main content of your website.</p>
<!-- Add more content here -->
</section>
<script>
window.onscroll = function() {
// Get the header
var header = document.querySelector("header");
// Get the offset position of the header
var sticky = header.offsetTop;
// Add the "sticky" class to the header when you reach its scroll position
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
};
</script>
</body>
</html>
In this example, the header has a position: fixed;
property, and a z-index
property to ensure it stays at the top and doesn’t overlap with other elements. The JavaScript code adds a “sticky” class to the header when the user scrolls down past its original position. The additional margin-top in the section is added to prevent content from being hidden behind the fixed header. Customize the styles and content to fit your website’s design.