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>
<div class="content">
<!-- Your website content here -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget ex eget leo feugiat vestibulum ut et nisi. Suspendisse potenti.</p>
</div>
<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 0;
text-align: center;
width: 100%;
position: fixed;
top: 0;
z-index: 1000;
}
.content {
padding-top: 80px; /* Adjust according to the height of your header */
/* Other styles for your content */
}
JavaScript (script.js):
window.onscroll = function() {stickyHeader()};
var header = document.getElementById("header");
var sticky = header.offsetTop;
function stickyHeader() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
In this code:
- The CSS is used to style the header and ensure it stays at the top of the viewport using the
position: fixed
property. - The JavaScript is used to add or remove a “sticky” class to the header based on the user’s scroll position. When the user scrolls past the header, the sticky class is added, making the header stick to the top of the viewport.
- The HTML provides the structure for the webpage, including the header and content sections.
- Ensure to adjust the
padding-top
value in the.content
class to match the height of your header.
<a href=”https://www.fox29.com/news/peco-customers-unable-to-view-accounts-due-to-error-with-billing-system”>Source</a>
Leave a Reply