No this is not about using position: fixed by default. Take a look at this page as example, scroll down, and see the top-left. Notice the issue metadata stick on top? As far as I know there is no pure CSS for this task, it uses onscroll to do the job.
The following element would stick on top after you scroll down enough:
Here is the source code and you can play with jsFiddle:
<div id="sticky-anchor"></div>
<div id="sticky">This will stay at top of page</div>
<style>
#sticky {
padding: 0.5ex;
width: 600px;
background-color: #000;
color: #fff;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
</script>I didn’t invent this, the original code is from an answer1 on Stack Overflow, and that seems to be from Stack Overflow’s code, but with a few of my own modifications. The code requires jQuery.
The #sticky-anchor is for providing an offset reference, so we can compare with and know if visitor scrolls down far enough. If so, the #sticky would be applied with an CSS class, which makes it sticky to the page; if not, then remove the CSS class, so it can revert to what it should be when the page just loaded. This way make the code more cleaner.
z-index is better to be applied since other elements may have that, make sure the number is high enough so #sticky would be on top of others.
Related link: jQuery plugin sticky-div.
| [1] | I think it is a better (correct) answer to that question, too bad no one vote it up. |