Here's a simple example of creating a website's sticky header using HTML, CSS, and JavaScript.
This code creates a sticky header that becomes fixed at the top of
the page when you scroll down. Adjust styles and structure to fit your
website's design.
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="myHeader">
<h1>Your Website</h1>
</header>
<!-- Rest of your website content goes
here -->
<script
src="script.js"></script>
</body>
</html>
CSS (styles.css):
body
{
margin: 0;
font-family: 'Arial', sans-serif;
}
header
{
background-color: #333;
color: white;
text-align: center;
padding: 10px;
}
/*
Add some space for the content to prevent it from being hidden behind the
sticky header */
body
{
padding-top: 60px;
}
JavaScript (script.js):
document.addEventListener("DOMContentLoaded",
function () {
var header =
document.getElementById("myHeader");
var sticky = header.offsetTop;
function handleScroll() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
window.onscroll = function () {
handleScroll();
};
});
CSS (styles.css) for sticky behavior:
/*
Add this at the end of styles.css */
.sticky
{
position: fixed;
top: 0;
width: 100%;
z-index: 1000;
}
0 Comments