JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
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 Navigation</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<!-- Content goes here -->
</body>
</html>
CSS
body {
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: white;
position: sticky;
top: 0;
}
nav {
display: flex;
justify-content: space-around;
align-items: center;
padding: 1rem 0;
}
ul {
list-style: none;
display: flex;
}
li {
margin-right: 20px;
}
a {
text-decoration: none;
color: white;
}
JavaScript
const navbar = document.getElementById("navbar");
const sticky = navbar.offsetTop;
function stickNavbar() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
}
window.onscroll = function () {
stickNavbar();
};