div that does not exceed certain limits

Asked

Viewed 378 times

4

Well, on that link :: http://voky.com.ua/crostini/ there is a menu that when loading the page is not fixed at the top of the screen, but when descending the page a little this menu appears and is fixed at the top. How do you do that?

  • 1

    Your question title doesn’t quite match what you’re actually asking. Ideally, make the title clearer.

1 answer

4


Online example on jsfiddle. I made an example as clean as possible to allow adaptation.

HTML

<div class="div1"></div>

<div id="nav">
    <ul>
        <li><a href="#">Link A</a></li>
        <li><a href="#">Link B</a></li>
        <li><a href="#">Link C</a></li>
        <li><a href="#">Link D</a></li>
    </ul>
</div>

<div class="div2"></div>

JS

$(function() {
    var offsetTop = $('#nav').offset().top;
    var navigation = function(){
        var scrollTop = $(window).scrollTop();

        if (scrollTop > offsetTop){
            $('#nav').css({ 'position': 'fixed', 'top':0, 'left':0 });
        }else{
            $('#nav').css({ 'position': 'relative' }); 
        }   
    };

    $(window).scroll(function(){
        navigation();
    });
});

CSS

*{margin:0; border:0; padding:0; font:12px Arial, Helvetica, sans-serif}
.div1{background:#669900; height:200px; width:100%}
.div2{background:#669900; height:700px; width:100%}

#nav{width:100%; height:50px; background:#fff;}
#nav ul{list-style:none; margin:0; padding:5px;}
#nav ul li{ margin:0; padding:0; display:inline; }
#nav ul li a{float:left; margin:0 5px; padding:0 10px; height:40px; line-height:40px; color:#fff; background:#333; text-decoration:none}
  • 1

    Perfect. Exactly what I wanted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.