This is some content 0
This is some content 1
This is some content 2
This is some content 3
This is some content 4
This is some content 5
This is some content 6
This is some content 7
This is some content 8
I would like to style my menu bar Like THIS. It\'s fixed to the top of the site when you scroll down and it isn\'t fixed where it is when the page is loaded.
How ca
Source: Creating a sticky nav css and jquery
HTML
This is some content 0
This is some content 1
This is some content 2
This is some content 3
This is some content 4
This is some content 5
This is some content 6
This is some content 7
This is some content 8
CSS
* {
font-family: Consolas,Sans-serif;
font-size: 10pt;
}
#menu {
position: absolute;
width: 100%;
}
#menu.out {
position: fixed;
}
#menu ul {
margin: 0;
padding: 1em .5em;
list-style: none;
background-color: #fc9;
}
#menu ul li {
display: inline-block;
}
#menu ul li a {
padding: 5px .5em;
}
#content {
background-color: #ebebee;
padding: 4em 1em 1em;
height: 900px;
}
JQuery:
var menu = $("#menu");
var ul = menu.find("ul");
var content = $("#content")[0];
var data = $("#data");
var menuHeight = menu[0].getBoundingClientRect().bottom;
var inView= true;
$(document).scroll(function(evt) {
evt.preventDefault();
var top = content.getBoundingClientRect().top;
var nextInView = top+menuHeight > 0;
if (inView ^ nextInView)
{
data.append("Switching.")
inView = nextInView;
if (inView)
{
menu.removeClass("out");
}
else
{
menu.addClass("out");
ul.hide().slideDown("fast");
}
}
});
Fiddle :Demo
Courtesy : Robert Koritnik
Hope this helps
Happy Coding