Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a header always in view

I am designing my website and I'm trying to find a way to keep a header always in the screen.

For an example, take a look at this extra long page on Wikia.com. Notice that when you scroll the page, the little toolbar down the bottom stays in one place. However, scroll to the bottom of the page and you will realize that the toolbar stays in a fixed position until it gets out of view.

This is what I would like to do, but in reverse. Have a header that stays in a fixed position on the web-page, but when it was not in view have it at the top.

I tried looking at an example on DynamicDrive.com (search for Dock Content Script, because I can't post another link), but I found that it was too jittery for me.

Can someone please help me do this?

Thanks in advance.
~DragonXDoom

P.S. Now that I notice, the How to Format box on the right of the submit question page has this effect.

like image 456
DragonXDoom Avatar asked Dec 30 '10 01:12

DragonXDoom


3 Answers

Always remember if you have to stick the header or footer { position : fixed; } can be used.

So apply CSS like this:

.header{
    top:0;
    width:100%;
    height:50px;
    position:fixed;  // this is the key
}
like image 179
Wazy Avatar answered Oct 31 '22 12:10

Wazy


HTML:

<div id="wrap">
    <div id="header"> HEADER </div>
    <div id="navigation"> NAVIGATION </div>
    <div id="content"> CONTENT  </div>        
</div>

JavaScript:

( function () {    
    var nav = $( '#navigation' )[0],
        top = $( nav ).offset().top,
        left,
        height = $( nav ).outerHeight(),
        width = $( nav ).width(),
        fixedClass = 'fixed';

    function pageOffset() {
        return window.pageYOffset || document.body.scrollTop;
    }

    $( window ).
            resize( function () {
                left = $( nav ).offset().left;
            }).
            scroll( function () {
                $( nav ).toggleClass( fixedClass, pageOffset() > top );

                if ( $( nav ).hasClass( fixedClass ) ) {
                    $( nav ).
                        css({ 'left': left, 'width': width }).
                        prev().css({ 'marginBottom': height });
                } else {
                    $( nav ).
                        prev().andSelf().removeAttr( 'style' );
                }
            }).
            trigger( 'resize' );    
})();

Live demo: http://jsfiddle.net/simevidas/Mx8hC/show/

like image 4
Šime Vidas Avatar answered Oct 31 '22 13:10

Šime Vidas


If you want it to be stuck to the top even when the user scrolls (i.e. stuck to the top of the browser window), use:

.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  margin: 0;
}

Or just to the of the the page:

.top-bar {
  margin: 0;
  width: 100%;
}
like image 4
bricker Avatar answered Oct 31 '22 11:10

bricker