I tried to make a navigation bar that sticks to the top, but it's not working. I also tried to make the div position:fixed to top, but the div overlaps with the others after scroll, so I gave up on the position:fixed. How do I get position:sticky to work?
Here is my code:
var navbar = $('header:first');
$(window).scroll(function() {
if (window.pageYOffset >= 120) {
$('#nav-hidden').css({
'display': 'none'
});
$('header:first').css({
'background': 'none',
'height': '20vh'
});
navbar.addClass('sticky')
} else {
$('#nav-hidden').css({
'display': 'inherit'
});
$('header:first').css({
'background': "linear-gradient(to bottom,rgba(255, 255, 255, 1.0) 40%,rgba(255, 255, 255, 0.5)), url('background.jpg') center no-repeat",
'height': '100vh',
'position': 'inherit'
});
navbar.removeClass("sticky");
}
});
* {
padding: 0;
margin: 0;
}
html body {
min-height: 100%;
height: 100%;
scroll-behavior: smooth;
}
header {
height: 100vh;
width: 100%;
position: inherit;
background: linear-gradient(to bottom, rgba(255, 255, 255, 1.0) 40%, rgba(255, 255, 255, 0.5)), url('background.jpg') center no-repeat;
background-size: cover;
}
nav {
padding: 3rem;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 1.6rem;
font-family: 'Roboto', sans-serif;
}
nav ul {
display: flex;
margin-top: auto;
}
nav ul li {
list-style: none;
}
nav ul li a {
padding: 2rem;
font-weight: bold;
color: rgba(1, 1, 1, .9);
}
.logo a {
color: rgba(1, 1, 1, 1);
font-weight: bolder;
font-size: 4rem;
}
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: none;
color: rgba(1, 1, 1, .8);
}
a:focus {
text-decoration: none;
color: rgba(1, 1, 1, .5);
}
#nav-hidden {
position: absolute;
text-align: left;
bottom: 60vh;
left: 8vw;
}
.container {
height: 100vh;
width: 100%;
padding-top: 20vh;
}
.sticky {
position: sticky;
position: -webkit-sticky;
top: 0;
width: 100%;
}
.content {
background: rgba(1, 1, 1, .2);
}
<!DOCTYPE html>
<html>
<head>
<title> Main</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<nav>
<h1 class="logo"><a href="Main.html">Tour</a></h1>
<ul class="header">
<li><a href="">Home</a></li>
<li><a href="">About us</a></li>
<li><a href="">Social Media</a></li>
<li><a href="">Comment</a></li>
<li><a href="">Share</a></li>
</ul>
</nav>
<div id="nav-hidden">Explore.</div>
</header>
<div class="container" class="content">hi</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script language="JavaScript" type="text/javascript" src="script.js"></script>
</body>
</html>