Here’s a simple example of a sticky header implemented using HTML, CSS, and JavaScript:
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<header class="sticky-header">
<h1>Sticky Header</h1>
</header>
<div class="content">
<p>This is some content.</p>
</div>
http://script.js
</body>
</html>
CSS (styles.css):
window.addEventListener('scroll', function() {
const header = document.querySelector('.sticky-header');
const scrollY = window.scrollY;
if (scrollY > 0) {
header.classList.add('scroll');
} else {
header.classList.remove('scroll');
}});
JavaScript (script.js):
body {
margin: 0;
font-family: Arial, sans-serif;
}
.sticky-header {
background-color: #333;
color: white;
text-align: center;
padding: 10px;
position: sticky;
top: 0;
z-index: 100;
}
.content {
padding: 20px;}
In this example, the sticky header will become fixed to the top of the viewport when the user scrolls down the page. The ‘scroll‘ event listener in JavaScript adds a class called “scroll” to the header when the user starts scrolling, allowing you to apply different styles when the header is in the sticky state.
Leave a comment