HTML:
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta name=viewport content=width=device-width, initial-scale=1.0>
<title>Sticky Header Example</title>
<link rel=stylesheet href=styles.css>
</head>
<body>
<header id=header>
<h1>Sticky Header Example</h1>
</header>
<main>
<p>This is some content...</p>
<!-- More content here -->
</main>
<script src=script.js></script>
</body>
</html>
CSS (styles.css):
body {
margin: 0;
font-family: Arial, sans-serif;
}
header {
background-color: #333;
color: #fff;
padding: 20px;
text-align: center;
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
transition: top 0.3s ease;
}
main {
padding-top: 80px; /* Adjust this value to prevent content from being hidden under the header */
}
JavaScript (script.js):
// Get the header
var header = document.getElementById(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. Remove sticky when you leave the scroll position
function stickyHeader() {
if (window.pageYOffset > sticky) {
header.style.top = 0;
} else {
header.style.top = -100px; // Adjust this value based on your header's height
}
}
// When the user scrolls the page, execute stickyHeader
window.onscroll = function() {
stickyHeader();
};
This code will create a sticky header that remains at the top of the page as the user scrolls down. Adjust the CSS and JavaScript as needed for your specific design and requirements.
Leave a Reply