How do I set a "horizontal menu" at the top of the window when scrolling the page?

44

I have a layout with a horizontal navigation bar at the top of the site, it has margin-top:100px , when scrolling the page the menu should be set at the top of the window but with margin-top:0 .

What is the best way to accomplish this?

    
asked by Paulo 04.02.2014 в 16:51
source

4 answers

31

You need to control when your menu reaches the top of the window and then change the menu position to fixed.

So $('#meuMenu').offset().top will give you distance to the top.

When the distance is

answered by 04.02.2014 / 17:41
source
5

If this is not what you want, here is an example:

Page HTML:

<div class="nav-container">
<div class="nav">
    <ul>
        <li><a href="">Home</a></li>
        <li><a href="">CSS</a></li>
        <li><a href="">PHP</a></li>
        <li><a href="">SEO</a></li>
        <li><a href="">jQuery</a></li>
        <li><a href="">Wordpress</a></li>
        <li><a href="">Services</a></li>
    </ul>
    <div class="clear"></div> /*clear floating div*/
</div>
</div>

To make the menu horizontal, you need the following CSS:

.nav-container{ background: url('images/nav_bg.jpg') repeat-x 0 0;}
    .f-nav{ z-index: 9999; position: fixed; left: 0; top: 0; width: 100%;} /* this make our menu fixed top */

.nav { height: 42px;}
    .nav ul { list-style: none; }
    .nav ul li{float: left; margin-top: 6px; padding: 6px; border-right: 1px solid #ACACAC;}
    .nav ul li:first-child{ padding-left: 0;}
    .nav ul li a { }
    .nav ul li a:hover{ text-decoration: underline;}

And a small code in javascript:

jQuery("document").ready(function($){

    var nav = $('.nav-container');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 136) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });

});

Source: link

    
answered by 04.02.2014 в 16:57
3

You can check this out:

$(window).on('scroll', function() {

    if($(this).scrollTop() >= $('.menu').offset().top) {

        $('.menu:not(.fixed)').addClass('fixed');

    } else $('.menu.fixed').removeClass('fixed');

});

In the CSS class "fixed" you can change the placement type and remove the margin.

    
answered by 04.02.2014 в 17:01
1

In fact, with HTML 5 and CSS 3 you do not have to do any JQUERY or anything like that. Twitter Bootstrap has a navbar like this. just use the expression "navbar-fixed-top" in the object

    
answered by 05.02.2014 в 16:32