David Gard
David Gard

Reputation: 12077

How to use CSS to stop an HTML element scrolling off the top of the screen

I'm trying to set the site name/logo and the navigation on my page so that when it hits the top of the page, it stays there instead of disappearing off the top of the screen. I've tried position: fixed;, but unless I'm missing somthing that is not what I need to do.

My layout is as follows, and it is header-top and header-nave that I wish to not disapear off the top of the page -

<header>
    <div id="header-top"></div>
    <div id="header-middle"></div>
    <div id="header-nav"></div>
</header>

Does anybody have any tips on this, or know if it is even possible with CSS? Either way, some pointers to tutorials or even the method to use to do this would be helpful.

Am open to JS if that is what is needed. Thanks.

Upvotes: 1

Views: 15979

Answers (2)

David Gard
David Gard

Reputation: 12077

Thanks to the helpful hints and pointers (@Wesley Terry and @eZakto), here is the JS that acheives exactly what I am looking to do.

$(function(){

    var top = $('#header-top-full-width');
    var nav = $('#header-nav-full-width');

    $(window).scroll(function(){

        if($(window).scrollTop() >= 90){
            border_bottom('0');
        } else if($(window).scrollTop() === 89){
            border_bottom('1');
        } else if($(window).scrollTop() === 88){
            border_bottom('2');
        } else if($(window).scrollTop() <= 87){
            border_bottom('3');
        }

        if($(window).scrollTop() >= 90){ // To far, the navigation needs to be set in place
            nav.css('position', 'fixed');
            nav.css('margin-top', '-90px');
            if($('#nav-spacer').length) { // Add a spacer so the height is correct if needs be
            } else {
                $('<div id="nav-spacer"></div>').insertAfter('#header-nav-full-width');
                $('#nav-spacer').css('height', '32px');
            }
        } else { // The navigation needs to just be static, so remove the spacer and make it static
            nav.css('position', 'static');
            nav.css('margin-top', '0');
            $('#nav-spacer').remove();
        }       
    });
});

Upvotes: 1

Wesley Terry
Wesley Terry

Reputation: 195

There are a bunch of demos on how to accomplish this. Basically you need to figure out how far down the window to start to make the nav "sticky" with fixed positioning.

Here's a link to a good demo on it: http://webdesign.tutsplus.com/tutorials/javascript-tutorials/create-a-sticky-navigation-header-using-jquery-waypoints/

Upvotes: 2

Related Questions