Make a nav bar stick
Solution 1:
$(document).ready(function() {
$(window).scroll(function () {
//if you hard code, then use console
//.log to determine when you want the
//nav bar to stick.
console.log($(window).scrollTop())
if ($(window).scrollTop() > 280) {
$('#nav_bar').addClass('navbar-fixed');
}
if ($(window).scrollTop() < 281) {
$('#nav_bar').removeClass('navbar-fixed');
}
});
});
html, body {
height: 4000px;
}
.navbar-fixed {
top: 0;
z-index: 100;
position: fixed;
width: 100%;
}
#body_div {
top: 0;
position: relative;
height: 200px;
background-color: green;
}
#banner {
width: 100%;
height: 273px;
background-color: gray;
overflow: hidden;
}
#nav_bar {
border: 0;
background-color: #202020;
border-radius: 0px;
margin-bottom: 0;
height: 30px;
}
.nav_links {
margin: 0;
}
.nav_links li {
display: inline-block;
margin-top: 4px;
}
.nav_links li a {
padding: 0 15.5px;
color: #3498db;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner">
<h2>put what you want here</h2>
<p>just adjust javascript size to match this window</p>
</div>
<nav id='nav_bar'>
<ul class='nav_links'>
<li><a href="url">Nav Bar</a></li>
<li><a href="url">Sign In</a></li>
<li><a href="url">Blog</a></li>
<li><a href="url">About</a></li>
</ul>
</nav>
<div id='body_div'>
<p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>
</div>
Solution 2:
add to your .nav css block the
position: fixed
and it will work
Solution 3:
I hope this can help someone. Determine the nav offset through js and then apply sticky position css to nav:
But first, we will define the styles in the stylesheet, like so.
.sticky {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
Then, we will apply that class to the navigation conditionally with jQuery.
$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});
Solution 4:
Just use z-index
CSS property as described in the highest liked answer and the nav bar will stick to the top.
Example:
<div class="navigation">
<nav>
<ul>
<li>Home</li>
<li>Contact</li>
</ul>
</nav>
.navigation {
/* fixed keyword is fine too */
position: sticky;
top: 0;
z-index: 100;
/* z-index works pretty much like a layer:
the higher the z-index value, the greater
it will allow the navigation tag to stay on top
of other tags */
}
Solution 5:
CSS:
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
}
Attribute position: fixed
will keep it stuck, while other content will be scrollable. Don't forget to set width:100%
to make it fill fully to the right.
Example