To achieve this functionality, you can utilize jQuery. Look up the offset().top
and scrollTop()
functions within jQuery. The basic idea is to adjust the element's position
property to fixed
when the space between the element and the top of the document diminishes and reaches zero.
$(document).ready(function()
{
window.holdOffset = $('#sticky_navigation').offset().top;
$(window).scroll(function()
{
sticky_navigation();
});
});
function sticky_navigation()
{
var scroll_top = $(window).scrollTop();
if (scroll_top > holdOffset)
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
else
$('#sticky_navigation').css({ 'position': 'relative' });
};
body
{
margin:0px;
}
p
{
margin-left:100px;
margin-right:100px;
}
#my_logo
{
font-size:80px;
}
#sticky_navigation_wrapper
{
width:100%;
height:50px;
}
#sticky_navigation
{
width:100%;
height:50px;
background:black;
}
#sticky_navigation ul
{
list-style:none;
margin:0;
padding:5px;
}
#sticky_navigation ul li a
{
display:block;
float:left;
margin:0 0 0 5px;
padding:0 20px;
height:40px;
font-size:24px;
color:#ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="demo.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="sticky-navigation.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="demo_top_wrapper">
<div id="demo_top">
<div class="demo_container">
<div id="my_logo">Site Logo</div>
</div>
</div>
<div id="sticky_navigation_wrapper">
<div id="sticky_navigation">
<div class="demo_container">
<ul>
<li><a href="#" class="selected">Link #1</a></li>
<li><a href="#">Link #2</a></li>
<li><a href="#">Link #3</a></li>
</ul>
</div>
</div>
</div>
</div>
<section id="main">
<div id="content">
<p><strong>Scroll down to see this navigation menu sticking to the top of the page.</strong></p>
...[content continues here]...
</div>
</section>
<script type="text/javascript" src="myscript.js"></script>
</body>
</html>